1, Judgment: if
1. Single branch mode
if Condition test then Command sequence fi
if Condition test ; then Command sequence fi
Case:
[root@localhost jiaofan]# cat b.sh #!/bin/bash if [ -z $1 ] then echo "Error: service name not entered" echo "Usage: script name server name" fi if systemctl is-active $1 &> /dev/null ; then echo "$1 Already started" else echo "$1 Not started" exit 1 fi if systemctl is-enabled $1 &>/dev/null ; then echo "$1 Yes, power on from option" else echo "$1 Not boot from option" fi [root@localhost jiaofan]# ./b.sh Error: service name not entered Usage: script name server name Not started [root@localhost jiaofan]# ./b.sh sshd sshd Already started sshd Yes, power on from option [root@localhost jiaofan]# ./b.sh mysql mysql Not started [root@localhost jiaofan]#
2. Double branch mode
if Condition test; then Command sequence 1 else Command sequence 2 fi
Case: one click source code installation nginx package
[root@localhost jiaofan]# vi install_nginx.sh #!/bin/bash #Function Description: one click source code to install nginx package #Define different color attributes setcolor_failure="echo -en \\033[91m" setcolor_success="echo -en \\033[32m" setcolor_normal="echo -en \\033[0m" #Determine whether to execute the script as Administrator if [[ $UID -ne 0 ]];then $setcolor_failure echo -n "Please run as Administrator" $setcolor_normal exit fi #Judge whether there is wget download tool in the system #wget uses the - c option to enable the breakpoint continuation function if rpm --quiet -q wget ; then wget -c http://nginx.org/download/nginx-1.21.6.tar.gz else $setcolor_failure echo -n "not found wget,Please download it first......" $setcolor_normal exit fi #If there is no nginx account, the script automatically creates the account if ! id nginx &> /dev/null ; then adduser -s /sbin/nologin nginx fi #Test whether the correct source package software exists #Before compiling and installing the source package, install the relevant dependent packages if [[ ! -f nginx-1.21.6.tar.gz ]];then $setcolor_failure echo -n "not found nginx Source package, please download it first......" $setcolor_normal exit else yum -y install gcc pcre-devel zlib-devel openssl-devel clear $setcolor_success echo -n "Next, it takes a few minutes to compile the installation nginx" $setcolor_normal sleep 6 tar -xf nginx-1.21.6.tar.gz #Compile the source package, install nginx, specify the account and group, specify the installation path, open the required modules, and disable the unnecessary modules cd nginx-1.21.6/ ./configure \ --user=nginx \ --group=nginx \ --prefix=/data/server/nginx \ --with-stream \ --with-http_ssl_module \ --with-http_stub_status_module \ --without-http_autoindex_module \ --without-http_ssi_module make make install fi if [[ -x /data/server/nginx/sbin/nginx ]];then clear $setcolor_success echo -n "One click deployment nginx Already completed" $setcolor_normal fi
3. Multi branch mode
if Condition test 1; then Command sequence 1 elif Condition test 2; then Command sequence 2 elif Condition test 3; then Command sequence 4 ... ... else Command sequence n fi
Case: the script automatically generates random numbers within 10 and judges the output results according to the user's input
[root@localhost jiaofan]# cat guess_num.sh #!/bin/bash #Function Description: the script automatically generates random numbers within 10 and judges the output results according to the user's input clear num=$[RANDOM%10+1] read -p "Please enter 1~10 Integer between:" guess if [ ${guess} -eq ${num} ] ; then echo "Congratulations, you guessed right, that's it $num" elif [ $guess -lt $num ];then echo "Oops,Guess it's small." else echo "Oops,Guess big." fi [root@localhost jiaofan]# ./guess_num.sh Please enter 1~10 Integer between: 8 Oops,Guess big. [root@localhost jiaofan]#
2, Select: case
End use;; Or &. If used;; Then it means that the matching is not carried out downward& Represents continuing to match.
case word in Mode 1:) Command sequence 1;; Mode 2:) Command sequence 2;; ... ... pattern*:) Command sequence n;; esac
case word in Mode 1|Mode 2|Mode 3:) Command sequence 1;; Mode 4|Mode 5|Mode 6:) Command sequence 2;; ... ... pattern*:) Command sequence n;; esac
[root@localhost jiaofan]# cat echo_menu.sh #!/bin/bash #Function Description: define the function menu, use the case statement to judge the menu item selected by the user, and realize the corresponding function clear echo -e "\033[42m---------------------------------\033[0m" echo -e "\e[2;10H Here is the menu\t\t" echo -e "#\e[32m 1.View network card information\e[0m #" echo -e "#\e[33m 2.View memory information\e[0m #" echo -e "#\e[34m 3.View disk information\e[0m #" echo -e "#\e[35m 4.see CPU information\e[0m #" echo -e "#\e[36m 5.View account information\e[0m #" echo -e "\033[42m---------------------------------\033[0m" echo read -p "Please enter the option [1]-5]: " key case $key in 1) ip a ;; 2) mem_liyonglv=`free -t | awk 'NR == 2 {printf("%.2f% "), $3/$2*100}'` mem=$(free | grep Mem | tr -s " " | cut -d" " -f7) echo "The remaining memory capacity of the machine is: ${mem}K. " echo "Native memory utilization: ${mem_liyonglv}. " ;; 3) root_free=$(df | grep /$ | tr -s " " | cut -d" " -f4) echo "The remaining capacity of the local root partition is: ${root_free}K. " ;; 4) cpu=$(uptime | tr -s " " | cut -d" " -f13) cpu_liyonglv=$(top -b -n1 | head -5 | grep ^%Cpu | awk '{printf("%.2f%"),100-$8}') echo "Local machine cpu 15min The average load is: $cpu. " echo "Local machine cpu The utilization rate is: $cpu_liyonglv. " ;; 5) login_number=$(who | wc -l) total_number=$(cat /etc/passwd | wc -l) echo "The current system account is $USER" echo "The number of accounts currently logged in to the system is: $login_number" echo "The total number of users in the current system is: $total_number";; *) echo "Input error, exceeding 1-5 Scope of";; esac [root@localhost jiaofan]# ./echo_menu.sh --------------------------------- Here is the menu # 1.View network card information # # 2.View memory information # # 3.View disk information # # 4.see CPU information # # 5.View account information # --------------------------------- Please enter the option [1]-5]: 2 The remaining memory capacity of this machine is 283784 K. Native memory utilization: 56.14% . [root@localhost jiaofan]#
Case 2: do not distinguish between y and yes
[root@localhost jiaofan]# sh case-demo3.sh Are you sure you want to perform this operation(y|n)y Note: what do you choose yes [root@localhost jiaofan]# sh case-demo3.sh Are you sure you want to perform this operation(y|n)no What do you choose no [root@localhost jiaofan]# cat case-demo3.sh #!/bin/bash #Function Description: interactive script to identify the user's input information #You can enter y or yes, case insensitive #You can enter n or no, case insensitive #Use | to separate multiple pattern matches, represent or relationships, and match any pattern successfully read -p "Are you sure you want to perform this operation(y|n)" key case $key in [Yy]|[Yy][Es][Ss]) echo "Note: what do you choose yes";; [Nn]|[Nn][Oo]) echo "What do you choose no";; *) echo "Invalid input";; esac [root@localhost jiaofan]#
3, Loop: for, while
for name [ in [ word jiaofan ... ] ] do Command sequence done
for name #< = = the defau lt value is$@ do Command sequence done
for (( i=1 ; i<=8 ; i++ )) do Command sequence done
while Conditional judgment do Command sequence done
Case 1: automatically generated number
[root@localhost ~]# cat chess.sh #!/bin/bash #Function Description: print chess board for i in {1..8} do for j in {1..8} do sum=$[i+j] if [[ $[sum%2] -ne 0 ]];then echo -ne "\e[41m \e[0m" else echo -ne "\e[47m \e[0m" fi done echo done
4, until and select
until is just the opposite of while. until is to exit the loop when the conditions are met.
until Conditional judgment do Command sequence done
select Variable name in Value list do Command sequence done
Case 1: understanding until
[root@localhost jiaofan]# ./until.sh 1 2 3 4 5 [root@localhost jiaofan]# cat until.sh #!/bin/bash #until statementexits the loop only when the condition is true i=1 until [[ $i > 5 ]] do echo $i let i++ done [root@localhost jiaofan]#
Case 2: understanding select
[root@localhost jiaofan]# cat b.sh #!/bin/bash select i in {1..4} do echo $i done [root@localhost jiaofan]# ./b.sh 1) 1 2) 2 3) 3 4) 4 #? 2 2 #? 4 4 #? ^C [root@localhost jiaofan]#
Case 3: understanding select
[root@localhost jiaofan]# cat a.sh #!/bin/bash echo "Please select an option as prompted" select item in "CPU" "ip" "mem" "exit" do case $item in "CPU") uptime;; "ip") ip a s;; "mem") free;; "exit") exit;; *) echo error; esac done [root@localhost jiaofan]# ./a.sh Please select an option as prompted 1) CPU 2) ip 3) mem 4) exit #? 1 16:35:55 up 6:35, 1 user, load average: 0.00, 0.01, 0.05 #? 4 [root@localhost jiaofan]#
5, Interrupt and exit: continue, break and exit
command | effect |
---|---|
continue | End the word cycle, for example, cycle 10 times, but don't cycle the third time. At this time, you can use this to jump out of the third cycle |
break | End the whole cycle |
exit | Exit the program, no matter how much has not been executed, it is over anyway |
Under normal conditions:
[root@localhost jiaofan]# ./cbe.sh * * * * * * * * * * * * * * * * * * * * * * * * * [root@localhost jiaofan]# cat cbe.sh #!/bin/bash #Test continue, break, exit for i in {1..5} do for ((j=0;j<5;j++)) do echo -n "* " done echo done
Case 2: continue test: when $I = 3 & & $J = 3, that is, when printing the third row and the third column, execute continue, and you can see that 33 is not printed
[root@localhost jiaofan]# ./cbe.sh 10 11 12 13 14 20 21 22 23 24 30 31 32 34 40 41 42 43 44 50 51 52 53 54 [root@localhost jiaofan]# cat cbe.sh #!/bin/bash #Test continue, break, exit for i in {1..5} do for ((j=0;j<5;j++)) do if [[ $i -eq 3 && $j -eq 3 ]] ;then continue fi echo -n "$i$j " done echo done [root@localhost jiaofan]#
Case 3: Break: when you encounter a break in the third case of each line, you can see that the loop directly jumps out, but the outer loop will still be executed. Break can jump out of its for loop.
[root@localhost jiaofan]# ./cbe.sh 10 11 12 20 21 22 30 31 32 40 41 42 50 51 52 [root@localhost jiaofan]# cat cbe.sh #!/bin/bash #Test continue, break, exit for i in {1..5} do for ((j=0;j<5;j++)) do if [[ $j -eq 3 ]] ;then break fi echo -n "$i$j " done echo done [root@localhost jiaofan]#
Case 4: Exit: in case of exit, exit the script directly
[root@localhost jiaofan]# ./cbe.sh 10 11 12 [root@localhost jiaofan]# cat cbe.sh #!/bin/bash #Test continue, break, exit for i in {1..5} do for ((j=0;j<5;j++)) do if [[ $j -eq 3 ]] ;then exit #< = = exit script directly fi echo -n "$i$j " done echo done [root@localhost jiaofan]#
6, IFS default separator
The internal variable IFS (internal field separator) is used in the Shell to determine the separator of the item list or value list. The default value of IFS is space, Tab tab or line break. When using the for loop to read the item list or value list, it will judge the number of values in the list according to the value of IFS, and finally determine the number of cycles.
For special control characters, you can set the separator as a special control character.
Control character | describe |
---|---|
\a | Bell ringer |
\b | Backspace backspace |
\f | Form Feed line break character, the cursor still stays at the original position |
\n | New Line newline, and the cursor moves to the beginning of the line |
\r | Return moves the cursor to the beginning of the line without wrapping |
\t | Horizontal Tab horizontal tab |
\v | Vertical Tab vertical tab |
\nnn | Any octal character |
Case 1: output view $IFS
[root@localhost ~]# echo $IFS #< = = the content cannot be displayed because the value of IFS is a space or Tab character. In addition, the value of IFS is a newline character, so there are blank lines [root@localhost ~]# printf "%s" $IFS #< = = printf also has no content [root@localhost ~]# printf "%s" "$IFS" | od -b #< = = convert to octal. 040 is the space bar, 011 is the Tab character, and 012 is the line feed character. 0000000 040 011 012
Case 2: modify IFS
[root@localhost ~]# OLD_IFS="$IFS" #< = = back up the original, or set the defau lt value yourself [root@localhost ~]# IFS=";" #< = = set the separator to ";" [root@localhost ~]# read -p "Please enter 3 numbers:" x y z #< = = test with space as separator Please enter 3 numbers: a b c [root@localhost ~]# echo $x a b c #< = = ABC gives you all three values x [root@localhost ~]# echo $y $z [root@localhost ~]# read -p "Please enter 3 numbers:" x y z #< = = test with semicolon as separator Please enter 3 numbers: a;b;c [root@localhost ~]# echo $x #< = = success a [root@localhost ~]# echo $y b [root@localhost ~]# echo $z c [root@localhost ~]# IFS="$OLD_IFS" #< = = restore the previous value.
Case 3: set IFS as special control character
error setting
[root@localhost ~]# IFS="\t" #Wrong setting. Actually, this is separated by the letter t [root@localhost ~]# read -p "please enter 3 numbers:" x y z Please enter 3 numbers: a b c #< = = the middle is separated by Tab [root@localhost ~]# echo $x #< = = the test resu lt is a setup error a b c [root@localhost ~]# echo $y $z [root@localhost ~]# read -p "Please enter 3 numbers:" x y z #< = = whether the test is separated by t Please enter 3 numbers: atbtc [root@localhost ~]# echo $x a [root@localhost ~]# echo $y b [root@localhost ~]# echo $z c
Correct setting: $'string' must be a single quotation mark
[root@localhost ~]# IFS=$"\t" #< = = double quotation mark setting error [root@localhost ~]# read -p "please enter 3 numbers:" x y z Please enter 3 numbers: a b c [root@localhost ~]# echo $x a b c [root@localhost ~]# IFS=$'\t' #< = = single quotation mark set successfully [root@localhost ~]# read -p "please enter 3 numbers:" x y z Please enter 3 numbers: a b c [root@localhost ~]# echo $x a [root@localhost ~]# echo $y b [root@localhost ~]# echo $z c [root@localhost ~]# IFS=$' \t\n' #< = = restore defau lt settings: spaces, Tab tabs, or line breaks.