Shell full analysis (3): Shell script program

I. Introduction

This article introduces the Shell script program, mainly including the flow control, function, input/output redirection, and file inclusion of the program.

2. Process Control in Shell Scripts

Program flow control generally includes three types: sequence, condition and loop. In fact, the sequence does not need to be mentioned. Basically, the program is written directly, and the conditions and sequence are mainly introduced.

2.1 Conditional judgment

Overall example:

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi
a=10
b=10
if [ $a -eq $b ]
  then echo  "equals"
elif [ $a -gt $b ]
  then echo "greater"
elif [ $a -lt $b ]
  then echo "lower"
else echo "not exist"
fi

Summary:
(1) Keywords: The sign of conditional judgment is if then fithat only with ifcan be called conditional judgment, but as long as it ifappears, thenand fiwill also appear, these three keywords are necessary for conditional judgment, and there are two more The optional is elifand else.
(2) Whether to have the executive body then: each if elifof the executive body must be brought in front thenof it, but elsethe executive body of is not required to be brought in front then.
(3) Whether the execution can be empty: If the elsebranch execution body is empty, this else should not be written, and an error will be reported.
(4) Judgment conditions (square brackets or test command): Square brackets represent judgment, which is equivalent to the test keyword. Judgment in the shell includes numerical judgment, string judgment and file judgment. Digital judgment and file judgment generally use square brackets [], character Double square brackets are used for string judgment [[]]. In addition, number judgment is used -eq -neas the judgment of equality/not equal, and string judgment is used as the judgment == !=of equality/not equal.

2.2 Cycle

Commonly used loops are for loop and while loop (util loop is not commonly used, it is useless to learn, ignore it), using for loop, while loop, plus two keywords break and continue is enough to write shell scripts.

Whether it is a for loop or a while loop, the loop body is wrapped by do...done, which is the sign of the loop body in the shell script, and the conditional judgment is wrapped by if...fi.

2.2.1 for loop

Sample program:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

Written in one line:for var in item1 item2 ... itemN; do command1; command2… done;

Thus, the for loop in the shell is similar to Java's foreach loop for collection frames and arrays.

In a shell script, a single line represents a single command without a semicolon, but if multiple commands are written on one line, you need to use a semicolon to separate multiple statements.

Requirement: output an array

This can be done with a for...in... loop

# foreach循环,输出数组中所有元素
array=(1 2 3)
for a in ${array[@]}
do
  echo $a
done

array=(1 2 3)
for a in ${array[*]}
do
  echo $a
done

## foreach循环
for a in 1 2 3
do 
  echo $a
done 

insert image description here

It can also be implemented with a for loop in C language, as follows:

# c语言编写for循环
for ((i=1;i<=3;i++))
do 
   echo $i
done

# c语言编写for循环,输出数组中所有元素
array=(1 2 3)
for ((i=0;i<${#array[*]};i++))
do
  echo ${array[i]}
done

for ((i=0;i<${#array[@]};i++))
do
  echo ${array[i]}
done

insert image description here

2.2.2 while loop

The while loop is used to continuously execute a series of commands and also to read data from an input file. Its syntax format is:

while condition
do
    command
done

The following is a basic while loop that tests for a condition that returns true if int is less than or equal to 5. int starts at 1 and is incremented by 1 each time the loop is processed. Running the above script returns the numbers 1 to 5, then terminates.

# while循环
i=1
while [ $i -le 5 ]
do 
 echo $i
 let i++
done

# while循环遍历数组
array=(1 2 3 4 5)
i=0
while [ $i -le ${
    
    #array[*]} ]
do
   echo ${array[i]}
   let i++
done

insert image description here

Note: The let command is a calculation tool in BASH, used to execute one or more expressions, and the variable calculation does not need to add $ to represent the variable. If the expression contains spaces or other special characters, it must be enclosed.

Syntax format let arg [arg ...]
Parameter description:
arg: expression to be executed

Example:
Self-addition operation: let no++
Self-subtraction operation: let no
– short form let no+=10, let no-=20, respectively equivalent to let no=no+10, let no=no-20.

3. Functions in Shell Scripts

3.1 Definition and calling of Shell functions

The linux shell can user-defined functions, which can then be called freely in shell scripts.

The definition format of a function in the shell is as follows:

[ function ] funname [()]
{
    
    
    action;
    [return int;]
}

As above, the square brackets/square brackets are optional. In the function definition, only the function name and the function body and the curly brackets/curly brackets surrounding the function body are required. Others:
(1) The function keyword is optional: yes With function fun() definition, you can also directly define fun() without the function keyword.
(2) Return The return value is optional: the return value can display return, if not, the result of the last command will be used as the return value.

funWithReturn(){
    
    
    echo "这个函数会对输入的两个数字进行相加运算..."
    echo "输入第一个数字: "
    read aNum
    echo "输入第二个数字: "
    read anotherNum
    echo "两个数字分别为 $aNum$anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
echo "输入的两个数字之和为 $? !"

The output is similar to the following:

这个函数会对输入的两个数字进行相加运算...
输入第一个数字: 
1
输入第二个数字: 
2
两个数字分别为 12 !
输入的两个数字之和为 3 !

Note 1: The function return value $?is .
Note 2: All functions must be defined before use. This means that the function must be placed at the beginning of the script and not available until the shell interpreter first discovers it. A function is called using only its function name.

3.2 Operation arguments in Shell functions

In the shell, you can pass arguments to a function when you call it. Inside the function body, the value of the parameter is obtained in the form of $n. For example, $1 represents the first parameter, and $2 represents the second parameter, as follows:

funWithParam(){
    
    
    echo "第一个参数为 $1 !"
    echo "第二个参数为 $2 !"
    echo "第十个参数为 $10 !"
    echo "第十个参数为 ${10} !"
    echo "第十一个参数为 ${11} !"
    echo "参数总数有 $# 个!"
    echo "作为一个字符串输出所有参数 $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

Output result:

第一个参数为 1 !
第二个参数为 2 !
第十个参数为 10 !
第十个参数为 34 !
第十一个参数为 73 !
参数总数有 11!
作为一个字符串输出所有参数 1 2 3 4 5 6 7 8 9 34 73 !

Note: $10The tenth parameter cannot be obtained, it is required to obtain the tenth parameter ${10}. When n>=10, you need to use ${n}to get the parameters.

The operation parameters in the Shell function include the following:

parameter handling illustrate
$# The number of arguments passed to the script or function
$* Displays all parameters passed to the script as a single string
$@ Same as $*, but used with quotes, returning each argument in quotes.
$$ The current process ID number of the script running
$! ID number of the last process running in the background

4. Input/Output Redirection in Shell Scripts

4.1 Redirection and redirection commands

Most UNIX system commands take input from your terminal and send the resulting output back to your terminal. A command usually reads input from a place called standard input, which by default happens to be your terminal. Likewise, a command usually writes its output to standard output, which is also your terminal by default.

Redirect means

The list of redirected commands is as follows:

Order illustrate
command > file Redirect output to file.
command < file Redirect input to file.
command >> file Redirect output to file in append mode.
n > file Redirect the file with file descriptor n to file.
n >> file Appends the file with file descriptor n to file.
n >& m Merge output files m and n.
n <& m Merge input files m and n.
<< tag Takes as input the content between the opening tag tag and closing tag tag.

4.2 Output redirection

Redirection is generally achieved by inserting specific symbols between commands. In particular, the syntax of these symbols is as follows: command1 > file1, this command executes command1 and stores the output in file1.

Note: Any existing content in file1 will be replaced by the new content. If you want to add new content at the end of the file, use the >> operator.

Execute the following who command, which redirects the complete output of the command to the users file (users): $ who > usersAfter execution, no information is output to the terminal because the output has been rewritten from the default standard output device (terminal) Directs to the specified file.

You can view the file contents with the cat command:

$ cat users
_mbsetupuser console  Oct 31 17:35 
tianqixin    console  Oct 31 17:35 
tianqixin    ttys000  Dec  1 11:33 

Output redirection will overwrite the file content, see the following example:

$ echo "www.csdn.com" > users
$ cat users
www.csdn.com

If you don't want the file content to be overwritten, you can use >> to append to the end of the file, for example:

$ echo "www.csdn.com" >> users
$ cat users
www.csdn.com
www.csdn.com

4.3 Input redirection

Like output redirection, Unix commands can also get input from a file. The syntax is: command1 < file1, so that the command that originally needed to get input from the keyboard will be transferred to the file to read the content.

Note: Output redirection is greater than sign (>), input redirection is less than sign (<).

Following the above example, we need to count the number of lines in the users file and execute the following command: $ wc -l usersoutput:2 users

It is also possible to redirect input to the users file: $ wc -l < usersoutput:2

Note: The results of the two examples above are different: the first example, will output the filename; the second will not, because it only knows to read from standard input.

For example: command1 < infile > outfile
the command replaces both input and output, executes command1, reads the contents of the file infile, and writes the output to outfile.

4.4 Three kinds of files

Typically, three files are opened when each Unix/Linux command is run:

Standard input file (stdin): The file descriptor of stdin is 0, and Unix programs read data from stdin by default.
Standard output file (stdout): The file descriptor of stdout is 1, and Unix programs output data to stdout by default.
Standard error file (stderr): The file descriptor of stderr is 2, and Unix programs write error information to the stderr stream.

By default, command > filestdout is redirected to file and command < filestdin is redirected to file.

If you want stderr to be redirected to file, you can write: $ command 2>file
If you want stderr to be appended to the end of file, you can write:$ command 2>>file

File descriptor 0 is usually standard input (STDIN), 1 is standard output (STDOUT), and 2 is standard error output (STDERR). So, the 2 here means the standard error file (stderr).

If you want to redirect stdout and stderr to file, you can write: $ command > file 2>&1or$ command >> file 2>&1

If you want to redirect both stdin and stdout, you can write: $ command < file1 >file2The command command redirects stdin to file1 and stdout to file2.

Five, the file in the shell script contains

Shell scripts can contain external scripts. This makes it easy to encapsulate some common code as a separate file. Shell files contain the following syntax:

. filename   # 注意点号(.)和文件名中间有一空格source filename

The . number here means source, which is similar to the import keyword in java, which means import.

Example
Create two shell script files.

The code of test1.sh is as follows:url="http://www.csdn.com"

The code of test2.sh is as follows:

#使用 . 号来引用test1.sh 文件
. ./test1.sh
echo "CSDN官网地址:$url"

or

# source ./test1.sh
echo "CSDN官网地址:$url"

Next, we add executable permissions to test2.sh and execute:

$ chmod +x test2.sh 
$ ./test2.sh 
CSDN官网地址:http://www.csdn.com

6. Epilogue

This article introduces the Shell script program, mainly including the flow control, function, input/output redirection, and file inclusion of the program.

Code every day, progress every day! !

Guess you like

Origin blog.csdn.net/qq_36963950/article/details/123941525