This paper first introduces what Shell programming is, and takes you to a quick start, then explains the basic syntax of Shell and focuses on analysis of usage with cases, including Shell flow control and custom functions. Suggested collection.
Who needs to learn Shell programming?
- Linux OPERATION and maintenance engineers: Write Shell programs to manage service clusters.
- Python and JavaEE programmers: write Shell scripts or server maintenance, such as a script to periodically back up a database.
- Big data Programmers: Write Shell programs to manage clusters.
What is a Shell?
Shell is a command interpretation power that provides users with a way to send requests to the Linux kernel to run program interface system level programs. Users can start, suspend, stop and even write some programs with Shell.
Shell programming quick start
Enter a Linux terminal and write a Shell script hello.sh:
#! /bin/bash echo 'hello world! 'Copy the code
Run:
# chmod +x hello.sh #./hello.shCopy the code
The terminal prints Hello World! .
Description:
#!
Tell the system what interpreter the script needs to execute.- File extension
.sh
It’s not mandatory. - Method 1 runs the interpreter directly,
hello.sh
As a parameter to the Shell interpreter. In this case, the Shell script does not need to specify the interpreter information, and the first line can be removed. - Method 2 Hello. sh runs as an executable, and the first line of the Shell script must specify the interpreter.
Shell variables
define
Shell variables are divided into system variables and custom variables. System variables include $HOME, $PWD, $USER, etc. Display all variables in the current Shell: set. The variable name can contain letters, digits, and underscores (_) and cannot start with a number.
The basic grammar
- Defining variables: Variable name = variable value. There can be no Spaces on both sides of the equal sign. Variable names are usually in uppercase.
- Delete variable: unset variable name.
- Declare static variables: readonly The name of a variable. Static variables cannot be unset.
- Use variable: $variable name
Assign a command return value to a variable (important)
- A= ‘ls’ backquotes, execute the command inside
- A=$(ls) is equivalent to backquotes
Shell environment variables
define
The basic grammar
- Export variable name = variable value, and output Shell variables as environment variables.
- Source Indicates the path of the configuration file. The modified configuration takes effect immediately.
- Echo $variable name to check whether the environment variable takes effect
Positional parameter variable
The basic grammar
- $n: $1 indicates the command itself, $1-$9 indicates the first through ninth parameters, and above 10 parameters are in curly braces, such as ${10}.
- $* : all parameters in the command line, and all parameters are considered as a whole.
- $@ : all parameters in the command line and treat each parameter separately.
- $# : Indicates the number of all parameters.
Example:
Write the Shell script positionpara. sh to output the parameters entered by the command line.
#! /bin/bash # Echo $0 $1 $2 echo $* echo $@echo Number of parameters =$#Copy the code
Run:
# chmod +x positionPara.sh
# ./positionPara.sh 10 20
Copy the code
Running results:
Positionpara. sh 10 20 10 20 10 20 20 Number of parameters =2Copy the code
Predefined variable
define
A variable directly referenced in a Shell script prior to assigning a definition.
The basic grammar
- ? : INDICATES the PID process ID of the current process.
- $! : INDICATES the PID process ID of the last background process.
- $? : Indicates the return status of the last command executed. 0 indicates that the command is correctly executed. Non-0 indicates that the command fails to be executed.
Example:
Write the Shell script Prepara.sh to output information about the parameters entered from the command line.
#! /bin/bash echo Current process id =? # & : Run the program in the background./hello.sh & echo The last process number =$! Echo last command result =$?Copy the code
Running results:
Current process NUMBER =41752 Last process number =41753 Result of last command executed =0 # hello world!Copy the code
The operator
The basic grammar
- $((expression)) or $[expression]
- Expr m + n Note there must be Spaces between expr operators
- expr m – n
- Expr \*, /, % represent multiplication, division, mod respectively
The instance
# 1 way $(()) echo $(((2 + 3) * 4)) # $2 ways [], recommend echo $/ (2 + 3) * 4 # use expr TEMP = ` expr 2 + 3 ` echo ` ` expr $TEMP \ * 4Copy the code
conditional
The basic grammar
[condition] Notice the Spaces before and after the condition. Returns 0 if not null, 0 is true, otherwise false.
The instance
#! /bin/bash if ['test01' = 'test'] then echo = fi # 20 > 10 if [20 -gt 10] then echo > fi # If there is a file/root/shell/a.t xt if [-e/root/shell/a.t xt] then echo 'existence' fi if [' test02 '=' test02 '] && echo 'hello' | | echo If 'world' then echo 'is satisfied, execute' fi 'Copy the code
Running results:
If the greater than Hello condition is met, execute the following statementCopy the code
Process control
If judgment
The basic grammar
If [conditional judgment]; Then program FI # or (recommended) if elif then program FICopy the code
The instance
Write a Shell program: if the input parameter is greater than 60, output “pass”, otherwise output “fail”.
#! /bin/bash if [$1-ge 60] then echo elif [$1-lt 60] then echo "failCopy the code
Case branch
The basic grammar
Case $name in "value 1") if the value of the variable is equal to value 1, execute procedure 1; "Value 2") if the variable value is equal to value 2, then procedure 2 here is executed; . Omit other branches... *) If the variable value is not equal to the value listed above, execute the procedure here; esacCopy the code
The instance
If the command line parameter is 1, Monday is displayed. If the command line parameter is 2, Tuesday is displayed. If the command line parameter is other, Other is displayed.
Case $1 in "1") echo echo; "2") echo Tuesday; *) echo other; esacCopy the code
The for loop
The basic grammar
For variable name in value 1 value 2 value 3... Done # syntax 2 for ((initial value; Cyclic control conditions; Variable change)) do program doneCopy the code
The instance
-
Prints the parameters entered on the command line.
#! / bin/bash # use of $* for I "$*" in the do echo "the arg is $I" done echo "= = = = = = = = = = = = = = = = = =" use $@ # for j $@ do echo "in the arg is $j" doneCopy the code
Run result (review the difference between $* and $@) :
the arg is 1 2 3 ================== the arg is 1 the arg is 2 the arg is 3 Copy the code
-
Prints the value incremented from 1 to 100.
#! /bin/bash SUM=0 for ((i=1; i<=100; i++)) do SUM=$[$SUM+$i] done echo $SUMCopy the code
The while loop
The basic grammar
While [conditional] do the procedure doneCopy the code
The instance
Prints the value incremented from 1 to 100.
#! /bin/bash SUM=0 i=0 while [ $i -le $1 ] do SUM=$[$SUM+$i] i=$[$i+1] done echo $SUMCopy the code
Read console input
The basic grammar
Read (option)(parameter) option
- -p: indicates the prompt for specifying the read value
- -t: indicates the wait time (s) for the read value. If the read value is not entered within the specified time, the read value will not be waited.
parameter
- Variable name: The variable name of the read value
The instance
Read the console and enter a num value.
#! /bin/bash read -p "num1=" num1 echo" $num1 "read-t 10 -p" num2=" num2 echo "$num2=" num2 echo" $NUM2"Copy the code
Running results:
Please enter a number num1=10 The value of num1 you entered is: 10 Please enter a number num2=20 the value of num2 you entered is: 20Copy the code
function
Like other programming languages, Shell programming has system functions and custom functions. This article only mentions two commonly used system functions.
The system function
- Basename, deletes all parts of the path before the last/(including /), often used to get the file name.
The basic grammar
- basename [pathname] [suffx]
- basename [string] [suffx]
- If suffx is specified, the suffix for pathName or string is also dropped.
The instance
# basename /usr/bin/sort sort # basename include/stdio.h stdio.h basename include/stdio.h .h stdio Copy the code
- Dirname, delete all parts of the path after the last/(including /), often used to obtain the file path.
The basic grammar
- dirname pathname
- If the path does not contain /, ‘.’ (the current path) is returned.
The instance
# dirname /usr/bin/ /usr # dirname dir1/str dir2/str dir1 dir2 # dirname stdio.h . Copy the code
Custom function
The basic grammar
[ function ] funname[()] { Action; [return int;] } # call funname parameter 1 parameter 2...Copy the code
The instance
Computes the sum of the input two parameters.
#! /bin/bash function getSum(){SUM=$[$n1+$n2] echo "SUM=$SUM"} read-p "N2 # call getSum $n1 $n2Copy the code
A: congratulations! You already know the basic Shell syntax, so getting started is easy. To explore more advanced usage, learn advanced with me. Now that you’ve seen this, give each other a thumbs up