Quick start to shell Scripting (for new learners)


The following shell commands are gitbash installed on windows can execute successfully. The single and double quotation marks under linux may be different.

Common basic commands

Commands: let

let command is a tool for calculation in BASH, which is used to execute one or more expressions. It is not necessary to add $to represent variables in variable calculation.

#!/bin/bash
m=1
while(($m<=5))
do
    echo $m
    let m=m+1
done

# results of enforcement
1
2
3
4
5

expr command

expr command is a manual command line counter, which is used to find the value of expression variable under UNIX/LINUX. It is generally used for integer value and string.

Calculate string length
expr length 'this is a test'

# results of enforcement
14
Grab string
expr substr 'this is a test' 1 3

# results of enforcement
thi

# Counting starts from 1, front closed and back closed
Grab the position where the first character number string appears
expr index 'sarasara'  a

# results of enforcement
2
Integer operation
expr 14 % 9
# results of enforcement
5

expr 10 + 10
# results of enforcement
20

expr 1000 + 900
# results of enforcement
1900

expr 30 / 3 / 2
# results of enforcement
5

expr 30 \* 3 
# Execution result (when using a multiplier sign, its specific meaning must be masked with a backslash. Because the shell may misunderstand the meaning of displaying an asterisk)
90

Shell variable

Define variables

When defining a variable, the variable name is not marked with a dollar sign

your_name="zhangsan"

Note that there can be no spaces between variable names and equal signs, which may be different from all programming languages you are familiar with. Meanwhile, the naming of variable names must follow the following rules:

  • Naming can only use English letters, numbers and underscores. The first character cannot start with a number.
  • There can be no space in the middle. You can use underscore.
  • Punctuation cannot be used.
  • Keywords in bash cannot be used (you can use the help command to view reserved keywords).

Use variables

Use a defined variable, as long as the dollar sign is added in front of the variable name, such as:

your_name="Zhang San"
echo $your_name
echo ${your_name}

The curly braces outside the variable name are optional, whether they are added or not. The curly braces are added to help the interpreter identify the boundary of the variable.

It is recommended to add curly braces to all variables, which is a good programming habit.

Defined variables can be redefined, such as:

your_name="baidu"
echo $your_name
your_name="alibaba"
echo $your_name

#Output results
baidu
alibaba

read-only variable

Use the readonly command to define a variable as a read-only variable. The value of a read-only variable cannot be changed.

#!/bin/bash
myUrl="https://www.google.com"
readonly myUrl
myUrl="https://www.baidu.com"

#Execution result:
myUrl: readonly variable

Delete variable

Use the unset command to delete variables. Syntax:

unset variable_name

The variable cannot be used again after being deleted. The unset command cannot delete read-only variables.

myUrl="https://www.baidu.com"
unset myUrl
echo $myUrl

#Execution result:
No output

Variable type

When you run the shell, there are three variables at the same time:

  • 1) Local variables local variables are defined in scripts or commands and are only valid in the current shell instance. Programs started by other shells cannot access local variables.
  • 2) Environment variables all programs, including those started by the shell, can access environment variables. Some programs need environment variables to ensure their normal operation. Shell scripts can also define environment variables when necessary.
  • 3) shell variable shell variable is a special variable set by the shell program. Some of the shell variables are environment variables and some are local variables. These variables ensure the normal operation of the shell

Shell string

String is the most commonly used and useful data type in shell programming (there are no other types to use except numbers and strings). String can use single quotation marks, double quotation marks or no quotation marks.

Single quotation mark

str='this is a string'

Restrictions on single quote strings:

  • Any character in the single quotation mark will be output as it is, and the variable in the single quotation mark string is invalid;
  • A single single quotation mark cannot appear in a single quotation mark string (nor after using an escape character for single quotation marks), but it can appear in pairs and be used as string splicing.

Double quotation mark

your_name="zhangsan"
str="Hello, I know you are \"$your_name\"! \n"
echo -e $str

#Output result:
Hello, I know you are "zhangsan"! 

Advantages of double quotation marks:

  • There can be variables in double quotation marks
  • Escape characters can appear in double quotation marks

Splice string

your_name="zhangsan"
# Use double quotation mark splicing
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting  
echo $greeting_1
# Use single quotation mark splicing
greeting_2='hello, '$your_name' !'
greeting_3='hello, ${your_name} !'
echo $greeting_2  
echo $greeting_3

#Execution result:
hello, zhangsan !
hello, zhangsan !
hello, zhangsan !
hello, ${your_name} ! #A variable in a single quoted string is not valid

Get string length

string="abcd"
echo ${#string} 

#Output results 
4

Extract substring

The following example intercepts 4 characters from the second character of the string:

string="zhangsan is a great man"
echo ${string:1:4} 

#results of enforcement
hang  #The index value of the first character before closing and after closing is 0.

Find substring

Find the position of the character m or i or o (calculate which letter appears first):

string="zhangsan is a great man"
echo `expr index "$string" mio` 

#Output results
10 

#Resolution:
Which letter appears first, output its position (take) string The letters in the match one by one mio,Output the index if it matches the last one)
The first index of the string is 1
expr In expression ` It's a back quote, not a single quote '

Shell array

bash supports one-dimensional arrays (multi-dimensional arrays are not supported) and does not limit the size of the array.

Similar to C language, the subscripts of array elements are numbered from 0. The subscript is used to obtain the elements in the array. The subscript can be an integer or arithmetic expression, and its value should be greater than or equal to 0.

Define array

In the Shell, the array is represented by brackets, and the array elements are separated by the "space" symbol. The general form of defining an array is:

Array name=(Value 1 value 2 ... value n)

For example:

array_name=(value0 value1 value2 value3)

perhaps

array_name=(
value0
value1
value2
value3
)

You can also define each component of the array separately:

array_name[0]=value0
array_name[1]=value1
array_name[n]=valuen

echo ${array_name[n]}
#Output result:
valuen  #There is no limit to the range of subscripts

Continuous subscripts may not be used, and the range of subscripts is unlimited.

Read array

The general format for reading array element values is:

${Array name[subscript]}

For example:

valuen=${array_name[n]}

Use the @ symbol to get all the elements in the array, for example:

echo ${array_name[@]}

Gets the length of the array

The method of obtaining the length of the array is the same as that of the string, for example:

# Gets the number of array elements
length=${#array_name[@]}
# perhaps
length=${#array_name[*]}
# Gets the length of a single element of the array
lengthn=${#array_name[n]}

Shell comments

Lines beginning with # are comments and will be ignored by the interpreter.

Set multi line comments by adding a # number to each line, like this:

#--------------------------------------------
# This is a comment
# author: wo
# site: www.baidu.com

What if you encounter a large piece of code that needs to be annotated temporarily during the development process and cancel the annotation later?

Adding a # symbol to each line is too laborious. You can enclose this section of code to be annotated with a pair of curly braces and define it as a function. If there is no place to call this function, this code will not be executed and achieve the same effect as the annotation.

multiline comment

Multiline comments can also use the following formats:

:<<EOF
 Note Content ...
Note Content ...
Note Content ...
EOF

EOF can also use other symbols:

:<<'
Note Content ...
Note Content ...
Note Content ...
'

:<<!
Note Content ...
Note Content ...
Note Content ...
!

Shell pass parameters

When executing the Shell script, we can pass parameters to the script. The format of parameters obtained in the script is: $n. N represents a number, 1 is the first parameter of executing the script, 2 is the second parameter of executing the script, and so on

We pass three parameters to the script and output them respectively, where $0 is the file name of the execution (including the file path):

# The execution file is: test sh
echo "Executed file name: $0";
echo "The first parameter is: $1";
echo "The second parameter is: $2";

#Execute executable command:
./test.sh 1 2 3  #Send 3 parameters to the command

#Execution result:
./test.sh  # $0 is the file name of the execution (including the file path)
1  #First parameter
2  #Second parameter

In addition, there are several special characters for processing parameters:

Parameter processingexplain
$#Number of parameters passed to the script
$*Displays all parameters passed to the script in a single string. If "$*" is enclosed by ",", output all parameters in the form of "$1 $2... $n".
$$The ID number of the current process that the script is running
$!ID number of the last process running in the background
$@And ∗ mutually with , but yes send use Time plus lead number , and stay lead number in return return each individual ginseng number . as " *Same, but use it in quotation marks and return each parameter in quotation marks. As“ * same, but use quotation marks and return each parameter in quotation marks. If "@" is enclosed by "", "$1““ 2 " ... " 2" ... " 2. Output all parameters in the form of "..." n ".
$-Displays the current options used by the Shell, and set command Same function.
$?Displays the exit status of the last command. 0 indicates no error, and any other value indicates an error.
# The execution file is: test sh
echo "The first parameter is: $1";
echo "The number of parameters is: $#";
echo "The parameters passed are displayed as a string: $*";

#Execute command
./test.sh 1 2 3

#results of enforcement
 The first parameter is: 1
 Number of parameters: 3
 The parameters passed are displayed as a string: 1 2 3

$differs from $@:*

  • Same point: all parameters are referenced.
  • Difference: only in double quotation marks. Assuming that three parameters 1, 2 and 3 are written when the script is running, then "*" is equivalent to "1, 2 and 3" (passing a parameter, a string with spaces), and "@" is equivalent to "1", "2" and "3" (passing three parameters).
# The execution file is: test sh
echo "-- \$* demonstration ---"
for i in "$*"; 
do
    echo $i
done

echo "-- \$@ demonstration ---"
for i in "$@"; 
do
    echo $i
done

#Execute command
./test.sh 1 2 3

#results of enforcement
-- $* demonstration ---
1 2 3
-- $@ demonstration ---
1
2
3

Shell basic operator

Like other programming languages, Shell supports a variety of operators, including:

  • Arithmetic operator
  • Relational operator
  • Boolean operator
  • String operator
  • File test operator

Native bash does not support simple mathematical operations, but can be implemented by other commands, such as awk and expr, which are most commonly used.

expr is an expression calculation tool, which can be used to complete the evaluation of expressions.

For example, add two numbers (note that the back quote * ` * is used instead of the single quote * '*):

val=`expr 2 + 2`
echo "The sum of the two numbers is : $val"

#results of enforcement
 The sum of the two numbers is : 4

Two points to note:

  • There should be spaces between expressions and operators. For example, 2 + 2 is wrong and must be written as 2 + 2, which is different from most programming languages we are familiar with.
  • The complete expression should be included. Note that this character is not a common single quotation mark, but under the Esc key.

Arithmetic operator

The following table lists the commonly used arithmetic operators, assuming that variable a is 10 and variable b is 20:

operatorexplaingive an example
+additionexpr $a + $b results in 30.
-subtractionexpr $a - $b results in - 10.
*multiplicationexpr $a \* $b results in 200.
/divisionexpr $b / $a results in 2.
%SurplusExpr $B% $a results in 0.
=assignmenta=$b assigns the value of variable b to a.
==equal. Used to compare two numbers and return true if they are the same.[$a == $b] returns false.
!=Unequal. It is used to compare two numbers. If they are different, it returns true.[$a! = $b] returns true.

**Note: * * conditional expressions should be placed between square brackets with spaces, for example:[ a = = a== a==b] is wrong and must be written as [$a == $b].

a=10
b=20

val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"

val=`expr $a \* $b`
echo "a * b : $val"

val=`expr $b / $a`
echo "b / a : $val"

val=`expr $b % $a`
echo "b % a : $val"

if [ $a == $b ]
then
   echo "a be equal to b"
fi
if [ $a != $b ]
then
   echo "a Not equal to b"
fi

#results of enforcement
a + b : 30
a - b : -10
a * b : 200
b / a : 2
b % a : 0
a Not equal to b

be careful:

  • The multiplication sign (*) must be preceded by a backslash () to realize multiplication;
  • if... then... fi is a conditional statement, which will be explained later.
  • In MAC, the expr syntax of shell is $((expression)), where "*" in the expression does not need the escape symbol "".

Relational operator

Relational operators only support numbers, not strings, unless the value of the string is a number.

The following table lists the common relational operators, assuming that variable a is 10 and variable b is 20:

operatorexplaingive an example
-eqCheck whether the two numbers are equal, and return true if they are equal.[$a -eq $b] returns false.
-neDetect whether two numbers are not equal, and return true if they are not equal.[$a -ne $b] returns true.
-gtCheck whether the number on the left is greater than that on the right. If so, return true.[$a -gt $b] returns false.
-ltCheck whether the number on the left is less than that on the right. If so, return true.[$a -lt $b] returns true.
-geCheck whether the number on the left is greater than or equal to that on the right. If so, return true.[$a -ge $b] returns false.
-leCheck whether the number on the left is less than or equal to that on the right. If so, return true.[$a -le $b] returns true.
a=10
b=20

if [ $a -eq $b ]
then
   echo "$a -eq $b : a be equal to b"
else
   echo "$a -eq $b: a Not equal to b"
fi

if [ $a -ne $b ]
then
   echo "$a -ne $b: a Not equal to b"
else
   echo "$a -ne $b : a be equal to b"
fi

if [ $a -gt $b ]
then
   echo "$a -gt $b: a greater than b"
else
   echo "$a -gt $b: a Not greater than b"
fi

if [ $a -lt $b ]
then
   echo "$a -lt $b: a less than b"
else
   echo "$a -lt $b: a Not less than b"
fi

if [ $a -ge $b ]
then
   echo "$a -ge $b: a Greater than or equal to b"
else
   echo "$a -ge $b: a less than b"
fi

if [ $a -le $b ]
then
   echo "$a -le $b: a Less than or equal to b"
else
   echo "$a -le $b: a greater than b"
fi

#results of enforcement
10 -eq 20: a Not equal to b
10 -ne 20: a Not equal to b
10 -gt 20: a Not greater than b
10 -lt 20: a less than b
10 -ge 20: a less than b
10 -le 20: a Less than or equal to b

Boolean operator

The following table lists the common Boolean operators, assuming that variable a is 10 and variable b is 20:

operatorexplaingive an example
!If the expression is true, it returns false; otherwise, it returns true.[!] true returns false.
-oOr operation. If an expression is true, it returns true.[$a -lt 20 -o $b -gt 100] returns true.
-aAnd operation, both expressions return true only when they are true.[$a -lt 20 -a $b -gt 100] returns false.
a=10
b=20

if [ $a != $b ]
then
   echo "$a != $b : a Not equal to b"
else
   echo "$a == $b: a be equal to b"
fi

if [ $a -lt 100 -a $b -gt 15 ]
then
   echo "$a Less than 100 and $b Greater than 15 : return true"
else
   echo "$a Less than 100 and $b Greater than 15 : return false"
fi

if [ $a -lt 100 -o $b -gt 100 ]
then
   echo "$a Less than 100 or $b Greater than 100 : return true"
else
   echo "$a Less than 100 or $b Greater than 100 : return false"
fi

if [ $a -lt 5 -o $b -gt 100 ]
then
   echo "$a Less than 5 or $b Greater than 100 : return true"
else
   echo "$a Less than 5 or $b Greater than 100 : return false"
fi

#results of enforcement
10 != 20 : a Not equal to b
10 Less than 100 and 20 more than 15 : return true
10 Less than 100 or more than 20 : return true
10 Less than 5 or 20 more than 100 : return false

Logical operator

The following describes the logical operators of Shell, assuming that variable a is 10 and variable b is 20:

operatorexplaingive an example
&&Logical AND[[$a - LT 100 & & $B - GT 100]] returns false
||Logical OR[[$a - LT 100 | $B - GT 100]] returns true
a=10
b=20

if [[ $a -lt 100 && $b -gt 100 ]]
then
   echo "return true"
else
   echo "return false"
fi

if [[ $a -lt 100 || $b -gt 100 ]]
then
   echo "return true"
else
   echo "return false"
fi

#results of enforcement
 return false
 return true

String operator

The following table lists the common string operators, assuming that variable a is "abc" and variable b is "efg":

operatorexplaingive an example
=Check whether two strings are equal, and return true if they are equal.[$a = $b] returns false.
!=Detect whether two strings are not equal, and return true if they are not equal.[$a! = $b] returns true.
-zCheck whether the string length is 0, and return true if it is 0.[- z $a] returns false.
-nCheck whether the string length is not 0, and return true if it is not 0.[- n "$a"] returns true.
$Check whether the string is empty. If not, return true.[$a] returns true.
a="abc"
b="efg"

if [ $a = $b ]
then
   echo "$a = $b : a be equal to b"
else
   echo "$a = $b: a Not equal to b"
fi
if [ $a != $b ]
then
   echo "$a != $b : a Not equal to b"
else
   echo "$a != $b: a be equal to b"
fi
if [ -z $a ]
then
   echo "-z $a : String length is 0"
else
   echo "-z $a : String length is not 0"
fi
if [ -n "$a" ]
then
   echo "-n $a : String length is not 0"
else
   echo "-n $a : String length is 0"
fi
if [ $a ]
then
   echo "$a : String is not empty"
else
   echo "$a : The string is empty"
fi

#results of enforcement
abc = efg: a Not equal to b
abc != efg : a Not equal to b
-z abc : String length is not 0
-n abc : String length is not 0
abc : String is not empty

File test operator

The file test operator is used to detect various properties of Unix files.

Attribute detection is described as follows:

Operatorexplaingive an example
-b fileCheck whether the file is a block device file. If so, return true.[- b $file] returns false.
-c fileCheck whether the file is a character device file. If so, return true.[- c $file] returns false.
-d fileCheck whether the file is a directory. If so, return true.[- d $file] returns false.
-f fileCheck whether the file is an ordinary file (neither a directory nor a device file). If so, return true.[- f $file] returns true.
-g fileCheck whether the SGID bit is set in the file. If so, return true.[- g $file] returns false.
-k fileCheck whether the file has a sticky bit set. If so, return true.[- k $file] returns false.
-p fileCheck whether the file is a famous pipeline. If so, return true.[- p $file] returns false.
-u fileCheck whether the SUID bit is set in the file. If so, return true.[- u $file] returns false.
-r fileCheck whether the file is readable. If so, return true.[- r $file] returns true.
-w fileCheck whether the file is writable. If so, return true.[- w $file] returns true.
-x fileCheck whether the file is executable. If so, return true.[- x $file] returns true.
-s fileCheck whether the file is empty (whether the file size is greater than 0). If it is not empty, return true.[- s $file] returns true.
-e fileCheck whether files (including directories) exist. If so, return true.[- e $file] returns true.

Other checkers:

  • -S: Determine whether a file is a socket.
  • -50: Detect whether the file exists and is a symbolic link.

The following code will detect various attributes of the file. The variable file represents the file C: \ users \ zzz \ desktop \ rmstest \ test txt,

file="C:\Users\zzz\Desktop\RmsTest\test.txt"

if [ -r $file ]
then
   echo "File readable"
else
   echo "File unreadable"
fi

if [ -w $file ]
then
   echo "File writable"
else
   echo "The file is not writable"
fi

if [ -x $file ]
then
   echo "Executable file"
else
   echo "The file is not executable"
fi

if [ -f $file ]
then
   echo "The file is ordinary"
else
   echo "The document is a special document"
fi

if [ -d $file ]
then
   echo "The file is a directory"
else
   echo "File is not a directory"
fi

if [ -s $file ]
then
   echo "File is not empty"
else
   echo "File is empty"
fi

if [ -e $file ]
then
   echo "File exists"
else
   echo "file does not exist"
fi

#Execution result:
File readable
 File writable
 File executable
 The file is ordinary
 File is not a directory
 File is not empty
 File exists

Shell echo command

The echo instruction of Shell is similar to the echo instruction of PHP, which is used for string output. Command format:

echo string

1. Display ordinary string:

echo "It is a test"

echo It is a test

#Double quotation marks can be omitted completely, and the execution effect of the two commands is the same
#Execution result:
It is a test

2. Display escape characters

echo "\"It is a test\""

echo \"It is a test\"

#Double quotation marks can also be omitted, and the execution effect of the two commands is the same
#results of enforcement
"It is a test"

3. Display variables

The read command reads a line from standard input and assigns the value of each field of the input line to a shell variable

#!/bin/sh
read name 
echo "$name It is a test"

Save the above code as test SH, name receives the standard input variable, and the result will be:

sh test.sh

#results of enforcement
zhangsan                     #Standard input
zhangsan It is a test        #output

4. Show line breaks

echo -e "OK! \n" # -e open escape
echo "It is a test"

#Output result:
OK!

It is a test

5. Display without line break

echo -e "OK! \c" # -e enable escape \ c do not wrap
echo "It is a test"

#Output result:
OK! It is a test

6. Display results directed to file

echo "It is a test" > myfile 

7. Output the string as it is without escaping or taking variables (use single quotation marks)

echo '$name\"'

#Output result:
$name\"

8. Display command execution results

echo `date`

#Execution result:
Fri Feb 18 15:49:47 2022

#Note: the back quotation mark `, not the single quotation mark ', is used here.

Shell test command

The test command in the Shell is used to check whether a condition is true. It can test values, characters and files.

Numerical test
parameterexplain
-eqEqual to true
-neNot equal to true
-gtGreater than is true
-geGreater than or equal to is true
-ltLess than is true
-leTrue if less than or equal to
num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

#results of enforcement
 The two numbers are equal!
String test
parameterexplain
=Equal to true
!=True if not equal
-z stringIf the length of the string is zero, it is true
-n stringTrue if the length of the string is not zero
num1="test1"
num2="test2"
if test $num1 = $num2
then
    echo 'Two strings are equal!'
else
    echo 'The two strings are not equal!'
fi

# results of enforcement
 The two strings are not equal!
File test
parameterexplain
-e file nameTrue if the file exists
-r file nameTrue if the file exists and is readable
-w file nameTrue if the file exists and is writable
-x file nameTrue if the file exists and is executable
-s file nameTrue if the file exists and has at least one character
-d file nameTrue if the file exists and is a directory
-f file nameTrue if the file exists and is a normal file
-c file nameTrue if the file exists and is a character type special file
-b file nameTrue if the file exists and is a block special file
cd /bin
if test -e ./a.sh
then
    echo 'file already exist!'
else
    echo 'file does not exist!'
fi

#Execution result:
file already exist

Shell also provides and (- a), or (- o), non (!) Three logical operators are used to connect test conditions, and their priority is:! Highest, - a second, and - o lowest

cd /bin
if test -e ./a.sh -o -e ./b.sh
then
    echo 'At least one file exists!'
else
    echo 'Neither file exists'
fi

#results of enforcement
 At least one file exists!

Shell array

Multiple values can be stored in the array. Bash Shell only supports one-dimensional arrays (multi-dimensional arrays are not supported), and the array size does not need to be defined during initialization.

Like most programming languages, the subscript of array elements starts with 0.

Shell arrays are represented by parentheses, and elements are separated by a "space" symbol.

Define array:

my_array=(A B "C" D)

You can also use subscript definitions:
array_name[0]=value0
array_name[1]=value1
array_name[2]=value2

Read array

${array_name[index]}

example:
my_array=(A B "C" D)
echo "The first element is: ${my_array[0]}"
echo "The second element is: ${my_array[1]}"
echo "The third element is: ${my_array[2]}"
echo "The fourth element is: ${my_array[3]}"

#Output results
 The first element is: A
 The second element is: B
 The third element is: C
 The fourth element is: D

Gets all elements in the array

Use * * @ or * * * to get all the elements in the array

my_array=(A B "C" D)
echo "The elements of the array are: ${my_array[*]}"
echo "The elements of the array are: ${my_array[@]}"

# Output result:
The elements of the array are: A B C D
 The elements of the array are: A B C D

Gets the length of the array

Using # to get the length of an array is the same as getting the length of a string

my_array=(A B "C" D)

echo "The number of array elements is: ${#my_array[*]}"
echo "The number of array elements is: ${#my_array[@]}"

Shell process control

The shell process control cannot be empty. If there is no statement execution in the else branch, do not write else

if else

if else syntax format:

if condition
then
    command1 
    command2
    ...
    commandN
else
    command
fi

if else-if else

If else if else syntax format:

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

The following examples judge the size relationship between two variables:

a=10
b=20
if [ $a == $b ]
then
   echo "a be equal to b"
elif [ $a -gt $b ]
then
   echo "a greater than b"
elif [ $a -lt $b ]
then
   echo "a less than b"
else
   echo "No conditions met"
fi

#Output results
a less than b

The if else statement is often used in conjunction with the test command:

num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
    echo 'Two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

#Execution result:
Two numbers are equal!

#if the condition is used, it is written as:
if  [ $num1 -eq $num2 ]  # There should be no fewer spaces on the left and right sides of brackets [], otherwise the syntax will report an error

#Using test, the use of spaces and brackets [] is relatively less strict, which can be written as:
if test $num1 -eq $[num2]
if test $num1 = $[ num2 ]
if test $[num1] == $[ num2 ]

for loop

The general format of for loop is:

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

# The in list can contain substitutions, strings, and file names.

The in list is optional. If it is not used, the for loop uses the positional parameter of the command line. eg:

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

#Output result:
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

Characters in sequential output string:

for str in This is a string
do
    echo $str
done

#Output result:
This
is
a
string

while statement

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

while condition
do
    command
done
m=1
while(($m<=5))
do
    echo $m
    let m=m+1
done

# The above example uses the Bash let command, which is used to execute one or more expressions. There is no need to add $to represent variables in variable calculation

# Output results
1
2
3
4
5

The while loop can be used to read keyboard information. In the following example, the input information is set to the variable site, and press to end the loop.

echo 'Press <CTRL-D> sign out'
echo -n 'Enter the name of your favorite website: '
while read site
do
    echo "yes! $site It's a good website"
done

#Output results
 yes! xxx It's a good website

until loop

The until loop executes a series of commands until the condition is true.

until loop and while loop are handled in the opposite way.

while loops are generally better than until loops, but in some cases - and only in rare cases - until loops are more useful.

until syntax format:

until condition
do
    command
done

condition is generally a conditional expression. If the return value is false, continue to execute the statements in the loop body, otherwise jump out of the loop.

a=0
until [ ! $a -lt 10 ]
do
    echo $a
    a=`expr $a + 3`
done
#Output result:
0
3
6
9


a=10
until [ $a -gt 20 ]
do
    echo $a
    let a=a+4
done
#Output result:
10
14
18

#be careful:
until and [ ] Spaces between, and[ ]The space between and expression cannot be more or less, otherwise various errors will be reported

case ... esac

Case... esac is a multi choice statement, which is similar to switch... Case statements in other languages. It is a multi branch selection structure. Each case branch starts with a right parenthesis and two semicolons;; Indicates break, that is, the end of execution. The whole case... esac statement will be jumped out, and esac (that is, the reverse of case) will be used as the end mark.

You can use a case statement to match a value with a pattern. If the match is successful, execute the matching command.

case... esac syntax format is as follows

case value in
 Mode 1)
    command1
    command2
    ...
    commandN
    ;;
Mode 2)
    command1
    command2
    ...
    commandN
    ;;
esac

As the first mock exam shows, the case must be the word in, and each mode must end with the right parenthesis. The first mock exam can be a variable or constant. The match is found to match a certain pattern and all commands are executed until then.

The value will detect each matching pattern. Once the pattern matches, the corresponding command of matching pattern will be executed, and other patterns will not be continued. If there is no matching pattern, use the asterisk * to capture the value, and then execute the following command.

The following script prompts you to enter 1 to 4 to match each pattern:

echo 'Enter a number between 1 and 4:'
echo 'The number you entered is:'
read aNum
case $aNum in
    1)  echo 'You chose 1'
    ;;
    2)  echo 'You chose 2'
    ;;
    3)  echo 'You chose 3'
    ;;
    4)  echo 'You chose 4'
    ;;
    *)  echo 'You didn't enter a number between 1 and 4'
    ;;
esac

#Output results
 Enter a number between 1 and 4:
The number you entered is:
3
 You chose 3
site="baidu"
case "$site" in
   "baidu") echo "Baidu search" 
   ;;
   "google") echo "Google search" 
   ;;
   "taobao") echo "TaoBao" 
   ;;
esac

#Output result:
Baidu search

Jump out of loop

In the process of loop, sometimes it is necessary to forcibly jump out of the loop when the loop end condition is not reached. The Shell uses two commands to realize this function: break and continue.

break command

The break command allows you to jump out of all loops (terminate the execution of all subsequent loops).

while :
do
    echo -n "Enter a number between 1 and 5:"
    read aNum
    case $aNum in
        1|2|3|4|5) echo "The number you entered is $aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5! game over"
            break
        ;;
    esac
done

#Output result:
Enter a number between 1 and 5:3
 The number you entered is 3!
Enter a number between 1 and 5:7
 The number you entered is not between 1 and 5! game over
continue

The continue command is similar to the break command, except that it will not jump out of all loops, only the current loop.

while :
do
    echo -n "Enter a number between 1 and 5: "
    read aNum
    case $aNum in
        1|2|3|4|5) echo "The number you entered is $aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5!"
            continue
            echo "game over"
        ;;
    esac
done

When a number greater than 5 is entered, the loop in this example will not end and the statement echo "game over" will never be executed.

Shell function

linux shell can user-defined functions, and then can be called freely in the shell script.

The definition format of functions in shell is as follows:

[ function ] funname [()]

{

    action;

    [return int;]

}

explain:

  • 1. It can be defined with function fun() or directly without any parameters.
  • 2. Parameter return, plus can be displayed: return returns. If not, the result of the last command will be used as the return value. Return followed by the value n(0-255)

The following example defines a function and calls it:

demoFun(){
    echo "This is my first shell function!"
}
echo "-----Function starts execution-----"
demoFun
echo "-----Function execution completed-----"

The following is a function with a return statement:

funWithReturn(){
    echo "This function adds the two input numbers..."
    echo "Enter the first number: "
    read aNum
    echo "Enter the second number: "
    read anotherNum
    echo "The two numbers are $aNum and $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
echo "The sum of the two numbers entered is $? !"

#Output result:
This function adds the two input numbers...
Enter the first number:
11
 Enter the second number:
22
 The two numbers are 11 and 22, respectively !
The sum of the two numbers entered is 33 !

The return value of the function is passed through $? To get it.

Note: all functions must be defined before use. This means that the function must be placed at the beginning of the script until it is first discovered by the shell interpreter. The calling function can only use its function name.

Note: $? It is only responsible for its previous instruction. Once the function returns and its return value is not saved into the parameter immediately, its return value will no longer pass $? get.

eg:

function demoFun1(){
    echo "This is my first shell function!"
    return `expr 1 + 2`
}

demoFun1
echo $?
echo $?

#Execution result:
This is my first shell function!
3
0

Function parameters

In Shell, when you call a function, you can pass parameters to it. Inside the function body, the value of the parameter is obtained in the form of $n. for example, $1 represents the first parameter, $2 represents the second parameter

Examples of functions with parameters:

funWithParam(){
    echo "The first parameter is $1 !"
    echo "The second parameter is $2 !"
    echo "The tenth parameter is $10 !"
    echo "The tenth parameter is ${10} !"
    echo "The eleventh parameter is ${11} !"
    echo "The total number of parameters is $# One! "
    echo "Output all parameters as a string $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73


#Execution result:
The first parameter is 1 !
The second parameter is 2 !
The tenth parameter is 10 !
The tenth parameter is 34 !
The eleventh parameter is 73 !
There are 11 parameters in total!
Output all parameters as a string 1 2 3 4 5 6 7 8 9 34 73 !

be careful, 10 no can Obtain take The first ten individual ginseng number , Obtain take The first ten individual ginseng number need want 10. The tenth parameter cannot be obtained. It is required to obtain the tenth parameter The tenth parameter {10} cannot be obtained. When n > = 10, ${n} needs to be used to obtain parameters.

In addition, there are several special characters for processing parameters:

Parameter processingexplain
$#The number of arguments passed to the script or function
$*Displays all parameters passed to the script in a single string
$$The ID number of the current process that the script is running
$!ID number of the last process running in the background
$@Same as $*, but use in quotation marks and return each parameter in quotation marks.
$-Displays the current options used by the Shell, which has the same function as the set command.
$?Displays the exit status of the last command. 0 indicates no error, and any other value indicates an error.

Whether the return value of function is true or false

The execution results of functions and commands can be used as conditional statements. Note that in the shell language, 0 represents true and values other than 0 represent false.

echo "Hello World !" | grep -e Hello
echo $?
#Execution result:
Hello World !
0

echo "Hello World !" | grep -e Bye
echo $?
#Execution result:
1

#Resolution:
# grep is a command to find a match from a given string.
# If a match is found, the matching part will be printed and the returned value $? Is 0. If it cannot be found, the return value is $? Is 1.
if echo "Hello World !" | grep -e Hello
then
    echo true
else
    echo false
fi
#Execution result:
Hello World !
true

#Resolution:
echo "Hello World !" | grep -e Hello The execution result of is 0, 0 represents true,So it will print first Hello World!,Then in if-else If the result in the statement is true, print it true. 
if echo "Hello World !" | grep -e Bye
then
    echo true
else
    echo false
fi
#Execution result:
false


#Resolution:
echo "Hello World !" | grep -e Bye The execution result is 1,1 representative false,So it won't print. stay if-else False in statement, print false. 
function demoFun1(){
    return 0
}

if demoFun1
then
    echo true
else
    echo false
fi

#results of enforcement
true

#Resolution:
demoFun1 Returns 0, which means true, if-else Print in statement true
function demoFun2(){
    return 12
}

if demoFun2
then
    echo true
else
    echo false
fi

#Execution result:
false

#Resolution:
demoFun2 Returns 12. The representative other than 0 is false, if-else Print in statement false. 

Shell file contains

Like other languages, shells can contain external scripts. This can easily encapsulate some common code as a separate file.

The syntax format contained in the Shell file is as follows:

. filename   # Note the dot (.) There is a space between and the file name

or
source filename

Create two shell script files.

test1. The SH code is as follows:

#!/bin/bash

url="http://www.baidu.com"

test2. The SH code is as follows:

#!/bin/bash

#use. Number to reference test1 SH file
. ./test1.sh

# Or use the following include file code
# source ./test1.sh

echo "website: $url"

Execute test2 SH, the results are as follows:

website: http://www.baidu.com

Shell redirection

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 happens to be your terminal by default. Similarly, a command usually writes its output to standard output. By default, this is also your terminal.

The list of redirection commands is as follows:

commandexplain
command > fileRedirect output to file.
command < fileRedirect input to file.
command >> fileRedirect the output to file as an append.
n > fileRedirect the file with file descriptor n to file.
n >> fileRedirect the file with file descriptor n to file by appending.
n >& mMerge the output files m and n.
n <& mMerge the input files m and n.
<< tagTake the content between the start tag and the end tag tag as input.

It should be noted that file descriptor 0 is usually standard input (STDIN), 1 is standard output (STDOUT), and 2 is standard error output (STDERR).

Output redirection

Redirection is usually achieved by inserting specific symbols between commands. In particular, the syntax of these symbols is as follows:

command1 > file1

eg:

echo "The website is: www.baidu.com" > output.txt

After execution, no information is output at the terminal because the output has been redirected from the default standard output device (terminal) to the specified file.

You can use the cat command to view the contents of the file:

cat output.txt

#results of enforcement
 The website is: www.baidu.com 

Output redirection will overwrite the contents of the file. If you don't want to overwrite, you can use > > to append to the end of the file

echo "The website is: www.ali.com" >> output.txt

In this way, two pieces of data will appear when cat is executed again

cat output.txt

#Execution result:
The website is: www.baidu.com 
The website is: www.ali.com

input redirection

Like output redirection, Unix commands can also get input from files. The syntax is:

command1 < file1

In this way, the command that needs to get input from the keyboard will be transferred to the file to read the content.

Note: the output redirection is greater than sign (>), and the input redirection is less than sign (<).

eg: count the number of lines in the users file and execute the following command:

wc -l users

#results of enforcement
2 users

You can also redirect input to the users file:

wc -l < users

#Output result:
2 

Note: the results of the above two examples are different: in the first example, the file name will be output; The second one won't, because it only knows what to read from standard input.

If the input and output are replaced at the same time, execute the command, read the contents from the file infile, and then write the output to the outfile.

command < infile > outfile

eg:

echo "The website is: www.baidu.com" > site
wc -l < site > output

#results of enforcement
#No results are displayed on the terminal. You can view the output file
#Resolution:
echo Print results to site File, right again site Count the number of lines in the file and output the results to output

We can see output: 
cat output
1

Redirect in-depth explanation

Typically, each Unix/Linux command runs with three files open:

  • 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. Unix programs output data to stdout by default.
  • Standard error file (stderr): the file descriptor of stderr is 2, and Unix program will write error information to stderr stream.

By default, command > file redirects stdout to file, and command < file redirects stdin to file.

If you want stderr to redirect to file, you can write this:

$ command 2>file

If you want stderr appended to the end of the file, you can write this:

$ command 2>>file

2 indicates standard error file (stderr).

If you want to merge stdout and stderr and redirect to file, you can write:

$ command > file 2>&1

perhaps

$ command >> file 2>&1

If you want to redirect both stdin and stdout, you can write this:

$ command < file1 >file2

The command redirects stdin to file1 and stdout to file2.

Here Document

Here Document is a special redirection method in Shell, which is used to redirect input to an interactive Shell script or program.

Its basic form is as follows:

command << delimiter
    document
delimiter

Its function is to pass the content (document) between two delimiter s to command as input.

be careful:

  • The delimiter at the end must be written in the top grid. There must be no characters in front of it and no characters after it, including spaces and tab indentation.
  • Spaces before and after the initial delimiter are ignored.

In the command line, calculate the number of lines of Here Document through the wc -l command:

$ wc -l << EOF
    Welcome to
    Baidu
    www.baidu.com
EOF
3          # The output result is 3 lines
$

We can also use Here Document in scripts, for example:

#!/bin/bash

cat << EOF
 Welcome to
 Baidu
www.baidu.com
EOF

#results of enforcement
 Welcome to
 Baidu
www.baidu.com

/dev/null file

If you want to execute a command, but you don't want the output to be displayed on the screen, you can redirect the output to / dev/null:

$ command > /dev/null

/dev/null is a special file, and the contents written to it will be discarded; If you try to read from this file, you can't read anything. However, the / dev/null file is very useful. Redirecting the output of the command to it will have the effect of "prohibiting output".

If you want to mask stdout and stderr, you can write as follows:

$ command > /dev/null 2>&1

**Note: * * 0 is standard input (STDIN), 1 is standard output (STDOUT), and 2 is standard error output (STDERR).

There can be no space between 2 and > here. When 2 > is integrated, it indicates error output.

Keywords: Linux shell bash

Added by KingPhilip on Wed, 23 Feb 2022 13:35:13 +0200