Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Shell programming case multi-branch statements, loop statements (for, while, etc.), Shell functions, Shell arrays

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

The structure of case statements:

Execute different command lines for different values of variables

case variable value in pattern 1) Command sequence 1 ;; Mode 2) Command Sequence 2 ;;.....*) Default command sequence esac

Examples:

Character type recognition:

prompting the user to input a character; judging whether the character is a letter, a number or other characters.

The script is as follows:

[root@localhost opt]# vim test01.sh#!/ bin/bashread -p "Please enter a character: " keycase $key in[a-z]|[A-Z]) echo "You entered a letter";;[0-9]) echo "You entered a number";;*) echo "You entered a special symbol"esac execution results as follows: [root@localhost opt]# chmod +x test01.sh [root@localhost opt]# ./ test01.sh Please enter a character: 3 You entered the number [root@localhost opt]# ./ test01.sh Please enter a character: d You entered the letter [root@localhost opt]# ./ test01.sh Please enter a character: #You entered the special symbol [root@localhost opt]#Loop statement for loop statement:

Loop structure: reading different variable values, used to execute the same set of commands one by one.

for variable name in value list do command sequence done

Example 1:

Batch Add Users:

User names are stored in the users.txt file, one per line; initial passwords are set to 123456; authentication scripts.

The specific experiments are as follows:

[root@localhost opt]# tail -5 /etc/passwdavahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologinpostfix:x:89:89::/var/spool/postfix:/sbin/nologintcpdump:x:72:72::/:/sbin/nologinjiang:x:1000:1000:jiang:/home/jiang:/bin/bashapache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin[root@localhost opt]# vim users.txt[root@localhost opt]# cat users.txt zhangsanlisiwangwuzhaoliu[root@localhost opt]# vim test02.sh[root@localhost opt]# cat test02.sh //shell script #!/ bin/bashTMP=$(cat /opt/users.txt)for USER in $TMPdo useradd $USER && echo "123456" | passwd --stdin $USER &> /dev/nulldone[root@localhost opt]# chmod +x test02.sh [root@localhost opt]# ./ test02.sh @localhost opt]# tail -5 /etc/passwdapache:x:48:48:Apache:/usr/share/httpd:/sbin/nologinzhangsan:x:1001:1001::/home/zhangsan:/bin/bashlisi:x:1002:1002::/home/lisi:/bin/bashwangwu:x:1003:1003::/home/wangwu:/bin/bashzhaoliu:x:1004:1004::/home/zhaoliu:/bin/bash[root @localhost opt]# [root@localhost opt]# su zhangsan[zhangsan@localhost opt]$ su lisi Password: [lisi@localhost opt]$

Example 2:

Check host status based on IP address:

IP addresses are stored in the ipadds.txt file, one per line; use ping to check connectivity for each host.

The shell script is as follows:

#!/ bin/bashTMP=$(cat /opt/ipadds.txt)for USER in $TMPdo ping -c 3 -i 0.2 -w 3 $USER &> /dev/null if [ $? -eq 0 ] then echo "$USER is up" else echo "$USER is down" fidonewhile loop statement:

Loop structure: repeatedly test a condition, as long as the condition is repeated execution.

while conditional test operation do command sequence done

Example 1:

Batch Add Users:

User names start with stu and are numbered numerically; add 10 users in total, stu1, stu2,... Stu20; initial password is set to 123456.

The shell script is as follows:

#!/ bin/bashPRE="stu"num=1while [ $num -le 10 ]do useradd $PRE$num echo "123456" | passwd --stdin $PRE$num &> /dev/dull let num++done

Example 2:

Guess the commodity price:

Random numbers are obtained through the variable RANDOM; users are prompted to guess and record the number of times, and exit the loop after guessing.

The shell script is as follows:

#!/ bin/bashTIMES=0PRICE=$(expr $RANDOM % 1000)while truedoread -p "Please guess the price (0-999):" moneylet TIMES++ if [ $money -gt $PRICE ] then echo "Your guess is too big" elif [ $money -lt $PRICE ] then echo "Your guess is too small" else echo "You guessed it correctly, the correct price is: $num" echo "You guessed $TIMES" break fi done until loop statement:

Loop structure: repeatedly test a condition, as long as the condition does not hold, repeated execution.

until conditional test operation do command sequence done

Example 1:

Calculate the sum of 1 - 50:

Calculate the sum of 1 to 50 by cyclic accumulation.

The experiment was as follows:

[root@localhost opt]# vim test04.sh[root@localhost opt]# cat test04.sh #!/ bin/bashi=0sum=0until [ $i -eq 51 ]do let sum+=i let i++doneecho $sum[root@localhost opt]# chmod +x test04.sh [root@localhost opt]# ./ test04.sh 1275[root@localhost opt]#

Example 2:

Send an online message to a specified user:

If the user is not online (not logged in to the system), try every 10 minutes until the user logs in to the system and sends the message; the user name and message are passed to the script through the location parameter.

The script is as follows:

#!/ bin/bashusername=$1#Determine message format if [ $# -lt 1 ];then echo "Usage:`basename $0` []" exit 1fi #Determine if the user exists if grep "^$username:" /etc/passwd > /dev/nullthen :else echo "User does not exist" exit 1fi #Is the user online, if not contact every 5 seconds until who| grep "^$username" > /dev/nulldo echo "User not online" sleep 5donemes=$*echo $mes |write $usernameShell function Shell function definition:

Command sequences are formatted together to facilitate reuse of command sequences.

[ function ] function name (){ command sequence [return x]} //Use return or exit to explicitly end a function calling a method of a function:

Function Name [Parameter 1] [Parameter 2]

Examples:

Sum of two numbers:

Define the function by sum () {}; sum two numbers by calling the function.

The experiment was as follows:

[root@localhost opt]# vim test06.sh [root@localhost opt]# cat test06.sh #!/ bin/bashsum(){ s=`expr $1 + $2` echo $s }[root@localhost opt]# chmod +x test06.sh [root@localhost opt]# ./ test06.sh @localhost opt]# sum 5 611[root@localhost opt]#Shell array application scenarios include: get array length get element length traverse element slice element replace element delete

...... Array Definition Method: Method 1

Array Name = (value0 value1 value2..)

methodology II

Array Name = ([0]=value [1]=value [2]=value...) //Array elements separated by spaces

Method 3 List Name ="value0 value1 value2... ArrayName = ($ListName) Method 4 ArrayName [0]="value" ArrayName [1]="value" ArrayName [2]="value" ArrayIncluded Data Type: Numeric TypeCharacter Type: Use " " or''Definition Get Array Length: Format: ${#ArrayName [@\*]} Instance: [root@localhost ~]# arr_amber =(1 2 3 4 5);[root@localhost ~]#arr_ length=${#arr_ number[*]}[root@localhost ~]# echo $arr length5 Read the assignment of a subscript: Format: ${array name [subscript]} Example: [root@localhost ~]#arr_ index2=${arr_ number[2]}[root@localhost ~]# echo $arr_ index23 Array traversal: [root@localhost ~]# for v in ${arr_ number[@]}> do> echo $V> done12345Shell Script Debugging echo command bash command

Syntax: sh [-nvx] script name

Common options:

-n: Do not execute script, only check syntax. No syntax problems do not display any content, there are problems prompt error. - v: When executing a script, display the script content first, and then execute the script. Give an error prompt when there is an error. - x: Output the executed script content to the screen. set command set -x: turn on adjustment mode set +x: turn off adjustment mode

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report