One , Condition selection , judge (if,case)

1.1 if Sentence usage and examples

When we need to judge in the script , We can use it if Statement . The specific grammar is as follows :

*   Single branch
if Judgment condition ;then

    Branch code with condition true
  fi

*   Bifurcations
if Judgment condition ; then

Branch code with condition true

else

The condition is a fake branch code

fi

*   Multi branch
if Judgment condition 1; then

Branch code with condition true
elif Judgment condition 2; then

Branch code with condition true
elif Judgment condition 3; then

Branch code with condition true

else

All of the above conditions are false branch codes
fi

In multi branch , The system will judge the conditions you write one by one , First encounter “ really ” Condition , Execute the branch , And then finish the whole thing if sentence .

be careful :1,if and fi They come in pairs

2,if Statements can be nested .

Example:

1) Judge the size of two numbers

 
1 #!/bin/bash 2 # Defining variables 3 read -p "Please input the first num:" num1 4 read -p
"Please input the second num:" num2 5 # Judge whether the number meets the standard 6 if [[ $num1 =~ ^[0-9]+$ &&
$num2 =~ ^[0-9]+$ ]];then 7 # Judge the size of two numbers and output the judgment result 8 if [ $num1 -lt $num2 ];then 9
echo "The num2 is biger than the num1" 10 elif [ $num1 -eq $num2 ];then 11 echo
"Two numbers equal" 12 else 13 echo "The num1 is biger than the num2" 14 fi 15
else 16 echo "Please enter the correct number" 17 fi 18 19 # Delete variable 20 unset num1
num2
 




2) Script /root/bin/createuser.sh, Realize the following functions : Use a user name as a parameter , If the user for the specified parameter exists , It shows that it exists , Otherwise, add it ; Display the id Number and other information

 
1 #!/bin/bash 2 # Defining variables 3 read -p " Please enter a user name :" name 4 # Determine whether the user name exists 5 if `id $name
&> /dev/null`;then 6 # If it exists , Then output ID Etc 7 echo " User presence , User's ID The information is :`id $name`" 8 else 9
# If it doesn't exist , Add users , Set password to random 8 position , Prompt to change password at next login , Display at the same time ID Etc 10 passwd=`cat /dev/urandom |tr
-cd [:alpha:] |head -c8` 11 `useradd $name &> /dev/null` 12 `echo "$passwd" |
passwd --stdin $name &> /dev/null` 13 echo " user name :$name password : $passwd" >> user.txt
14 `chage -d 0 $name` 15 echo " User added , User's ID The information is :`id $name` The password is :$passwd" 16 fi 17
18 # Delete variable 19 unset name passwd


1.2 case Usage and examples

When it comes to matching multiple conditions , We use it if It could be a lot of trouble , This is the time , We can use it case To write this script .case The specific grammar of :

case Variable reference in

PAT1)

branch 1

;;

PAT2)

branch 2

;;

...

*)

Default branch

;;

esac

be careful :1,case After each branch , Both are based on two “;” Ending ( The last one can be omitted )

      2,case and esac They come in pairs

Example:

1) Write a script , Prompt user for information , What determines its input is yes or no Or other information .

 
1 #!/bin/bash 2 # Defining variables 3 read -p "Yue ma?(yes or no):" ANS 4 # Convert uppercase to lowercase in variables 5
ans=`echo "$ANS" |tr [[:upper:]] [[:lower:]] ` 6 # Judge what the input information is and output the result 7 case $ans
in 8 yes|y) 9 echo "see you tonight" 10 ;; 11 no|n) 12 echo "sorry,I have no
time" 13 ;; 14 *) 15 echo "what’s your means?" 16 ;; 17 esac 18 19 # Delete variable 20
unset ANS ans
 



 

2) Script /root/bin/filetype.sh, Determine user input file path , Displays its file type ( ordinary , catalog , link , Other file types )

 
1 #!/bin/bash 2 read -p " Please enter a file path :" file 3 # Determine whether the file exists 4 `ls $file &>
/dev/null` 5 # If it exists , Determine the file type and output 6 if [ $? -eq 0 ];then 7 style=`ls -ld $file | head
-c1` 8 case $style in 9 -) 10 echo " This is a normal document " 11 ;; 12 d) 13 echo " This is a directory file " 14
;; 15 l) 16 echo " This is a link file " 17 ;; 18 *) 19 echo " This is another type of file " 20 ;; 21 esac 22
# If it doesn't exist , Prompt and exit 23 else 24 echo " The file does not exist " 25 exit 2 26 fi 27 28 # Delete variable 29 unset file
style
 



 

Two , Loop statement

    In our script , It is also necessary to run a piece of code repeatedly , here , We'll use loop statements . Loop statements , There are entry and exit conditions , The number of cycles is also divided into
Known in advance and unknown in advance ( Knowing in advance means that we know the exact number of cycles , Unknown in advance means that when a certain condition is satisfied, the cycle will be carried out , But the number of times is uncertain .). next , Let's take a look at the use of loop statements .

2.1 for loop

for The execution mechanism of the loop is : Assign the elements in the list to the “ Variable name ”; The loop body is executed once after each assignment ; Until the elements in the list run out , End of cycle . There are two basic grammars :

1)for Variable name in list ; do

Circulatory body

done

On the generating method of list , as follows :

① Give the list directly

② Integer list :

(a){start…end}

(b)`seq start end`

③ Command to return to list

    $(COMMAND)

④ use glob Wildcards such as :

      *.sh

⑤ Variable reference

$i,$*

2)for (( exp1; exp2; exp3 )); do

Circulatory body

done

  More clearly, it can be seen from the figure below :



Example:

1) Print multiplication tables

 
1 #!/bin/bash 2 # judge i Is the value of 1-9 3 for i in {1..9};do 4 # judge j Is the value of 1-$i 5 for j in
`seq 1 $i`;do 6 # If in , Then print i*j Value of 7 echo -en "$i*$j = $[$i*$j]\t" 8 done 9 echo 10
done 11 12 # Delete variable 13 unset i j
 



2) Enter a positive integer n, calculation 1+…+n And

 
1 #!/bin/bash 2 # Defining variables 3 sum=0 4 read -p " Please enter a positive integer :" num 5 # judge num Is it a positive integer 6 if
[[ $num =~ ^[[:digit:]]+$ ]];then 7 # If so , When i stay 1-$num Time , output sum value 8 for i in `seq 1
$num`;do 9 let sum+=$i 10 done 11 echo "sum=$sum" 12 # If not , Prompt output positive integer 13 else 14
echo " Please enter a positive integer !" 15 fi 16 17 # Delete variable 18 unset i sum num
 



2.2 while loop

while Cycle ratio for The cycle is a little more complicated , The specific grammar is as follows :

while CONDITION; do

      Circulatory body

done

be careful :1, Entry conditions :CONDITION by true; Exit conditions :CONDITION by false.

     
2,CONDITION Is the circulation control condition : Before entering the loop , Make a judgment first ; The judgment is made again after each cycle ; On condition that “true”, A loop is executed ; Know that the condition test status is “false” Terminate the cycle .

      3,CONDITION Generally, there should be loop control variables ; The value of this variable is constantly modified in the loop body .

Example:

1) calculation 100 Sum of all positive odd numbers within

 
1 #!/bin/bash 2 # Defining variables 3 i=1 4 sum=0 5 # When i<100 Time , Execute the following statement 6 while [ $i -le 100
];do 7 # When i When it is odd , another sum=sum+I,i=i+1 8 while [ $[i%2] -eq 1 ];do 9 let sum+=$i 10
let i+=1 11 done 12 # When i When not odd ,i=i+1 13 let i+=1 14 done 15 # Output results 16 echo
"sum=$sum" 17 18 # Delete variable 19 unset i sum
 



2.3 until loop

  until The syntax of loops and while The syntax of , But the entry and exit conditions are just the opposite , So it's not commonly used , As long as we understand . The specific grammar is as follows :

until CONDITION; do

  Circulatory body

done

be careful :1, Entry conditions :CONDITION by false; Exit conditions :CONDITION by true.

    2,do and done In pairs .

Example:

1) Cyclic output 1-10

 
1 #!/bin/bash 2 # Defining variables 3 i=1 4 # When i>10 Time , Exit loop 5 until [ $i -gt 10 ];do 6 #
output i Value of ,i=i+1 7 echo $i 8 let i+=1 9 done 10 11 # Delete variable 12 unset i


2.4 select loop

  select Loops are mainly used to create menus , Menu items in numerical order are displayed on the standard error , And display PS3 Prompt , Waiting for user input .

  The user enters a number in the menu list , Execute the appropriate command .

  User input is saved in built-in variables REPLY in .

  select The specific grammar of :

select variable in list; do

  Loop body command

done

be careful :①select It's a wireless loop , So remember to use break Command exit loop , Or use exit Command termination script . You can also press ctrl+c Exit loop .

②select Often with case Combined use .

③ And for The cycle is similar , It can be omitted in list, The location variable is used .

Example:

1) generate menu , And display the selected price .

 
1 #!/bin/bash 2 # definition PS3 Prompt 3 PS3="Please choose the menu:" 4 # Output menu 5 select
menu in yangroutang mifan hulatang jiaozi lamian huimian quit 6 do 7 # Judge the choice 8
case $REPLY in 9 1|4) 10 echo "The price is 20" 11 ;; 12 2|5) 13 echo "The
price is 12" 14 ;; 15 3|6) 16 echo "The price is 10" 17 ;; 18 7) 19 break 20 ;;
21 *) 22 echo "Choose error" 23 ;; 24 esac 25 done


2.5 Circulation supplement

2.5.1 Loop control statement continue&break

  Loop control statements are used in loop bodies , There are two common control statements ,continue and break. Now let's look at the difference :

continue Statement ends the loop , Go directly to the next round of judgment ; The innermost layer is the 1 layer .

break Statement ends with the entire loop , The innermost layer is the 1 layer .

Example:

1) seek (1+3+…+49+53+…+99) And

 
1 # Defining variables 2 sum=0 3 for ((i=1;i<=100;i++));do 4 # When i When it is odd , Carry on 5 if [ $[i%2] -eq
1 ];then 6 # When i=51 Time , Skip the loop 7 if [ $i -eq 51 ];then 8 continue 9 fi 10 let
sum+=$i 11 fi 12 done 13 echo "sum=$sum" 14 15 # Delete variable 16 unset i sum


2) seek (1+3+…+49) And

 
1 #!/bin/bash 2 # Defining variables 3 sum=0 4 for ((i=1;i<=100;i++));do 5 # When i When it is odd , Carry on 6
if [ $[i%2] -eq 1 ];then 7 # When i=51 Time , Jump out of the loop 8 if [ $i -eq 51 ];then 9 continue
10 fi 11 let sum+=$i 12 fi 13 done 14 echo "sum=$sum" 15 16 # Delete variable 17 unset i sum


2.5.2 Loop control command shift

  Position parameters can be used shift Command shift left , such as shift
3 Represents the original $4 Now it becomes $1, customary $5 Now it becomes $2 wait , customary $1,$2,$3 discard ,$0 Do not move . Without parameters shift The order is equivalent to shift 1.

 
We know , For positional variables or command line arguments , The number must be certain , Or when shell When the program does not know its number, it can assign all parameters to the variable together $*. When the user requests shell Without knowing the number of positional variables , It can also process the parameters one by one , In other words $1 After $2 etc. . stay shift Variables before command execution $1 The value of the shift The command is not available after execution .

Example:

1) test shift command
1 #!/bin/bash 2 until [ $# -eq 0 ];do 3 echo "The first argument is:$1,The
number of arguments is:$#" 4 shift 5 done


2.5.3 Signal capture trap

 
trap It's a shell Built in command , It is used to specify in the script how the signal is handled . such as , Press Ctrl+C Causes the script to terminate execution , The system actually sent it SIGINT Signal to script process ,SIGINT The default signal processing is to exit the program . If you want to be in Ctrl+C Do not exit the program , Then you have to use it trap Order to specify SIGINT How to deal with it .trap Commands are more than just processing Linux signal , It can also exit the script (EXIT), debugging (DEBUG), error (ERR), return (RETURN) And so on .

  The basic format syntax is as follows :

*   trap ‘ Trigger instruction ’ signal
  After the custom process receives the specified signal from the system , The trigger command will be executed , Instead of performing the original operation

*       trap ‘’ signal
  Operation of ignoring signal

*   trap ‘-’ signal
  Operation to restore the original signal

*       trap -p
  List actions for custom signals , That is, prompt the currently used trap What is the operation .

be careful :① Signal representation : It can be a full signal / Abbreviation / number ( The specific content is approved kill -l query )

② signal 9, Forced killing , We can't catch it .

Example:

1) Printing 0-9,ctrl+c Termination invalid

 
1 #!/bin/bash 2 # Set signal capture 3 trap 'echo press ctrl+c' 2 4 for
((i=0;i<10;i++));do 5 sleep 1 6 echo $i 7 done


 

2) Printing 0-9,3 before ctrl+c It cannot be terminated ,3 Then recover , Can terminate

 
1 #!/bin/bash 2 # Set signal capture 3 trap '' 2 4 trap -p 5 for ((i=0;i<3;i++));do 6
sleep 1 7 echo $i 8 done 9 trap '-' SIGINT 10 for ((i=3;i<10;i++));do 11 sleep
1 12 echo $i 13 done
 



 

2.5.4 Creating an infinite loop

  In our shell In script , You can create an endless loop , The specific settings are as follows :

  while true;do

    Circulatory body

  done

 

2.5.5 Execute parallel commands in loop statements

  When we need to execute a command in a script many times , We can set it to execute in parallel , This can greatly improve the running speed of the script
, But there are also disadvantages , In parallel , It's like opening a lot of seeds shell Together , Speed up , But the consumption of resources has also increased .

  Specific usage examples are as follows :

  for name in list ; do

    {

        Circulatory body

}$

  done

  wait

Example:

1) Search for your assigned IP( Subnet mask is 24 Of ) In the network segment of ,up Of ip address

 
1 #!/bin/bash 2 # Defining variables 3 read -p "Please input network (eg:172.17.0.1): " net
echo $net |egrep -o
"\<(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\>"
4 # Judge whether the network segment meets the specification 5 [ $? -eq 0 ] || ( echo "input error";exit 10 ) 6
# Determine which segments are in IP can ping through , Parallel execution 7 IP=`echo $net |egrep -o "^([0-9]{1,3}\.){3}"` 8 for i
in {1..254};do 9 { 10 ping -c 1 -w 1 $IP$i &> /dev/null && \ 11 echo "$IP$i is
up" 12 }& 13 done 14 wait 15 16 # Delete variable 17 unset net IP i

 
Three , Small supplement

      So much grammar , Let's have some fun ~ Here are a few interesting scripts I'd like to share with you

1) Print isosceles triangle ( With flashing )

 
1 #!/bin/bash 2 #num= Total bank number i= Which line j=* number k= Number of spaces 3 read -p " Please enter a number :" num 4 for i
in `seq 1 $num`;do 5 for k in `seq 1 $[$num-$i]`; do 6 echo -n " " 7 done 8 for
j in `seq 1 $[2*$i-1]`;do 9 if [ $j -eq 1 ] || [ $j -eq $[2*$i-1] ] || [ $i -eq
$num ];then 10 color=$[RANDOM%5+31] 11 echo -en "\033[1;$color;5m*\033[0m" 12
else 13 echo -n "*" 14 fi 15 done 16 echo 17 done 18 19 # Delete variable 20 unset num i j
k color
We can try the concrete effect by ourselves , Is the effect of the following two pictures :



 

2) Print chess board

 
1 #!/bin/bash 2 # Defining variables 3 color_1="\033[1;44m \033[0m" 4 color_2="\033[1;45m
\033[0m" 5 for (( i=1;$i <=8;i++ ));do 6 for (( j=1;$j <=8;j++ ));do 7 if [
$[$i%2] == 1 ] && [ $[$j%2] == 1 ];then 8 echo -en "$color_1$color_2" 9 elif [
$[$i%2] == 0 ] && [ $[$j%2] == 0 ];then 10 echo -en "$color_2$color_1" 11 fi 12
done 13 echo 14 done 15 16 # Delete variable 17 unset color_1 color_2 i j