One , Conditional selection , judge (if,case)

1.1 if Statement usage and examples

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

*   Single branch
if Judging conditions ;then

    Branch code with true condition
  fi

*   Bifurcate
if Judging conditions ; then

Branch code with true condition

else

Condition is false branch code

fi

*   Multibranched
if Judging conditions 1; then

Branch code with true condition
elif Judging conditions 2; then

Branch code with true condition
elif Judging conditions 3; then

Branch code with true condition

else

All of the above conditions are fake branch codes
fi

In multi branches , The system will judge the conditions you write one by one , First encounter “ really ” Conditional , Take the branch , And then end the whole thing if sentence .

be careful :1,if and fi In pairs

2,if Statements can be nested .

Example:

1) Determine 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 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 of the specified parameter exists , Show that it exists , Otherwise, add it ; Show 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 present , Then output ID Etc 7 echo " User exists , User's ID The information is :`id $name`" 8 else 9
# If not , Add user , Set password to random 8 position , Prompt to change password at next login , Show 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` Password is :$passwd" 16 fi 17
18 # Delete variable 19 unset name passwd

1.2 case Usage and examples

When multiple condition matching is involved , We use if It could be a lot of trouble , This time , We can use it case To write this script .case The specific syntax is as follows :

case Variable reference in

PAT1)

branch 1

;;

PAT2)

branch 2

;;

...

*)

Default branch

;;

esac

be careful :1,case After each branch , Two “;” Ending ( The last one can be omitted )

      2,case and esac In pairs

Example:

1) Write a script , Prompt user for information , Judge whether the 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 # Determine 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 , Show its file type ( ordinary , catalog , link , Other document types )

 
1 #!/bin/bash 2 read -p " Please enter a file path :" file 3 # Judge whether the file exists 4 `ls $file &>
/dev/null` 5 # If present , Determine 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 common document " 11 ;; 12 d) 13 echo " This is a catalog file " 14
;; 15 l) 16 echo " This is a linked file " 17 ;; 18 *) 19 echo " This is another type of file " 20 ;; 21 esac 22
# If not , 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 , There must be multiple operations on a certain piece of code , here , We're going to use loop statements . In loop statement , There are entry and exit conditions , The number of cycles is also divided into
Known in advance and unknown in advance ( Knowing in advance is that we know the exact number of cycles , Unknown in advance means to cycle when a certain condition is satisfied , But the number is uncertain .). next , Let's take a look at the usage of loop statements .

2.1 for loop

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

1)for Variable name in list ; do

Circulatory body

done

On the method of generating list , as follows :

① Give a 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 table

 
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 , 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 , 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 syntax 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 cycle control condition : Before entering the cycle , Make a judgment first ; After each cycle, the judgment will be made again ; The condition is “true”, Then execute a cycle ; Know that the condition test status is “false” End cycle .

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

Example:

1) calculation 100 Sum of all positive and 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 and while The syntax of is similar to , But the conditions for entry and exit are just the opposite , So not often , As long as we know . The specific syntax 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) Cycle 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 will be displayed on the standard error , And display PS3 Prompt , Waiting for user input .

  User enters a number in the menu list , Execute the corresponding command .

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

  select The specific syntax is as follows :

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 with exit Command termination script . You can also press ctrl+c Exit loop .

②select Frequently and case Joint use .

③ And for Circulation is similar , Can be omitted in list, Use position variable at this time .

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 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 statement used in loop body , There are two common control statements ,continue and break. Let's look at the difference between the two :

continue The end of the statement is the current cycle , Go straight to the next round of judgment ; The innermost layer is the 1 layer .

break The statement ends with the entire loop , The innermost layer is No 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 , Continue execution 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 , Continue execution 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 Cycle control command shift

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

 
We know , For position variables or command line parameters , The number must be definite , Or when shell When the program does not know its number, it can assign all parameters to variables together $*. When required by the user shell Without knowing the number of position variables , The parameters can be processed one by one , That is to say $1 After $2 etc . stay shift Variables before command execution $1 The value of shift Not available after command 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 in scripts to specify how signals are handled . such as , Press Ctrl+C Will cause the script to terminate execution , In fact, the system sent SIGINT Signal to script process ,SIGINT The default way to handle signals is to exit the program . If you want to Ctrl+C Do not exit the program , Then we have to use trap Command to specify SIGINT How to deal with it .trap Commands don't just deal with Linux signal , Can also exit the script (EXIT), debugging (DEBUG), error (ERR), return (RETURN) Specify the handling method in case of .

  The basic format syntax is as follows :

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

*       trap ‘’ signal
  Ignore signal operation

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

*       trap -p
  List actions for custom signals , Prompt the current trap What is the operation .

be careful :① Signal representation : It can be a complete signal / Shorthand / number ( Specific content passed kill -l query )

② signal 9, Forced killing , Can't capture .

Example:

1) Printing 0-9,ctrl+c Invalid termination

 
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 Cannot terminate ,3 Recovery after , 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 Create infinite loop

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

  while true;do

    Circulatory body

  done

 

2.5.5 Executing 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 scripts
, But there are also disadvantages , Parallel execution , It's like a lot of driving 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 own designated IP( Subnet mask is 24 Of ) In segments 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 conforms to the specification 5 [ $? -eq 0 ] || ( echo "input error";exit 10 ) 6
# Determine which segments are in the network 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 , Minor supplement

      Introduced so much grammar , Let's have some fun ~ Here are some interesting scripts for you to share

1) Print isosceles triangle ( With flicker )

 
1 #!/bin/bash 2 #num= General bank No i= Lines 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
You can try it yourself , It's 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

Technology
©2019-2020 Toolsou All rights reserved,
Unity Scene loading asynchronously ( Implementation of loading interface )ESP8266/ESP32 System : Optimize system startup time vue Of v-if And v-show The difference between JS How to operate college examination for the self-taught An overview of Marxism Faster RCNN Explanation of series algorithm principle ( note )CSS architecture design NOI2019 travels IAR Installation and use tutorial sort ( one ) bubble sort