Advanced classical use of Shell scripts

I. Selection and judgment of conditions

1. Select if

(1)

If judgment condition 1; Then condition is true branch code elif judgment condition 2; Then condition is true branch code elif judgment condition 3; Then condition true branch code else condition false branch code FICopy the code

Judge condition by condition, executing its branch when it first encounters a “true” condition, and then terminating the entire if.

(2) Classic cases:

# Judging age #! /bin/bash read -p "Please input your age: " age if [[ $age =~ [^0-9] ]] ; then echo "please input a int" exit 10 elif [ $age -ge 150 ]; then echo "your age is wrong" exit 20 elif [ $age -gt 18 ]; then echo "good good work,day day up" else echo "good good study,day day up" fiCopy the code

Analysis: please input age, first determine whether the input contains characters other than numbers, if yes, an error is reported; No, go ahead and see if it’s less than 150, if it’s greater than 18.

# Judge the score #! /bin/bash read -p "Please input your score: " score if [[ $score =~ [^0-9] ]] ; then echo "please input a int" exit 10 elif [ $score -gt 100 ]; then echo "Your score is wrong" exit 20 elif [ $score -ge 85 ]; then echo "Your score is very good" elif [ $score -ge 60 ]; then echo "Your score is soso" else echo "You are loser" fiCopy the code

Analysis: please input results, first judge whether the input contains characters other than numbers, there is an error; No, go ahead and see if it’s greater than 100, if it’s greater than 85, if it’s greater than 60.

2, condition judgment case

(1)

case $name in; PART1) cmd ;; PART2) cmd ;; *) cmd ;; Esac Note: Case supports glob style wildcards: *: Any length of any character? : any single character [] : specified within the scope of any single characters a | b: a or bCopy the code

(2) Cases:

# Judge yes or no #! /bin/bash read -p "Please input yes or no: " anw case $anw in [yY][eE][sS]|[yY]) echo yes ;; [nN][oO]|[nN]) echo no ;; *) echo false ;; esacCopy the code

Answer Y/ Y and yes by typing yes or no. The answer N/ N and No is No.

Two, four cycles

1, the for

(1)

① For name in the list; Done ② for (exp1; exp2; exp3 )) ; do cmd doneCopy the code

Execute it once, which is equivalent to embedding a while inside a for

③ Implementation mechanism:

  • Assign the elements in the list to the variable name in turn; A loop body is executed after each assignment; Until the list is exhausted, the loop ends
  • Lists can be represented by glob wildcards such as {1.. 10.}, * sh; Variable references can also be used, for example:seq 1 $name

(2) Cases

1+2+... +n) sum=0 Read -p "Please input a positive integer: "num if [[$num =~ [^0-9]]; then echo "input error" elif [[ $num -eq 0 ]] ; then echo "input error" else for i in `seq 1 $num` ; do sum=$[$sum+$i] done echo $sum fi unset zhiCopy the code

If the initial value of sum is 0, please input a number. First check whether the input contains any characters other than digits. Sum =sum+ I. Sum =sum+ I. At the end of the loop, sum is output.

1+2+... For ((I =1,num=0; i<=100; i++ )); Do [$[I %2] -eq 1] && let sum+= I done echo sum=$sum; When I <=100, enter the cycle, if I ÷2 mod =1, then sum=sum+ I, I = I +1.Copy the code

2, while

(1)

While loop control condition; The do loop doneCopy the code

Cyclic control conditions; Before entering the loop, make a judgment call; After each cycle, the judgment is made again; The condition “true” executes a loop; Terminate the loop until the conditional test status is “false”

(2) walk through each line of the file:

while read line; Do control variable initialization loop body done < / PATH/FROM/SOMEFILE or cat/PATH/FROM/SOMEFILE | while read the line; Do loop body doneCopy the code

Read each line in /PATH/FROM/SOMEFILE in turn and assign the line to the variable line

(3) Cases:

Sum =0 I =1 while [$i-le 100]; do if [ $[$i%2] -ne 0 ]; then let sum+=i let i++ else let i++ fi done echo "sum is $sum"Copy the code

Analysis: the initial value of sum is 0, the initial value of I is 1; Please input a number, first determine whether the input contains characters other than numbers, if yes, an error is reported; When I <100, enter the cycle and judge whether the mod of I ÷2 is not 0 and odd when it is not 0. Sum =sum+ I, I +1, is 0 and I +1. At the end of the loop, sum is printed.

3. Until loop

(1) Usage

Unitl cyclic condition; The do loop doneCopy the code

Entry condition: loop condition is true; Exit condition: loop condition is false; It’s the opposite of while, so you don’t use it very often, you just use while.

(2) Cases

Pgrep -u xiaoming &> /dev/null; Do sleep 0.5 done pkill -9 -u xiaomingCopy the code

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

4. Select loop and menu

(1) Usage

Select variable in list do doneCopy the code
  • ① The select loop is mainly used to create menus. The numeric order of menu items will be displayed on the standard error, and the PS3 prompt will be displayed, waiting for user input
  • ② Enter a number in the menu list and run the corresponding command
  • ③ User input is saved in the built-in variable REPLY
  • ④ Select is an infinite loop, so remember to use the break command to exit the loop, or use exit to terminate the script. You can also press CTRL + C to exit the loop
  • ⑤ Select and are often used in conjunction with case
  • ⑥ Similar to the for loop, you can omit the in list and use the position parameter

(2) Cases

PS3="Please choose the menu: " select menu in mifan huimian jiaozi babaozhou quit do case $REPLY in 1|4) echo "the price is 15" ;; 2|3) echo "the price is 20" ;; 5) break ;; *) echo "no the option" esac doneCopy the code

The PS3 is a select prompt, automatically generated menu, select 5break to exit the loop.

Some usage in the loop

1. Loop control statement

1. Grammar

Continue [N] : End the cycle of the NTH layer early and go straight to the next round of judgment; The innermost layer is the 1st layer break [N] : the NTH layer cycle is terminated in advance, and the innermost layer is the 1st layer

Example: while CONDTITON1; do CMD1 if CONDITION2; then continue / break fi CMD2 doneCopy the code

(2) Cases:

# 1) to (1 + 3 +... 49 53 + + +... +100) and #! /bin/bash sum=0 for i in {1.. 100}; do [ $i -eq 51 ] && continue [ $[$i%2] -eq 1 ] && { let sum+=i; let i++; } done echo sum=$sumCopy the code

Analysis: Do 1+2+… For the +100 loop, when I =51, skip this loop but continue the whole loop, resulting in sum=2449

# (2) o (1 + 3 +... +49) and #! /bin/bash sum=0 for i in {1.. 100}; do [ $i -eq 51 ] && break [ $[$i%2] -eq 1 ] && { let sum+=i; let i++; } done echo sum=$sumCopy the code

Analysis: Do 1+2+… For the +100 loop, when I =51, the whole loop is broken out, and the result is: sum=625

2. Loop the shift command

(1) Function

To move the list of arguments to the left a specified number of times, the left-most argument is removed from the list, and the following arguments continue through the loop

(2) Cases:

Create a user with a specified number of users. /binbash if [ $# -eq 0 ] ; then echo "Please input a arg(eg:`basename $0` arg1)" exit 1 else while [ -n "$1" ]; do useradd $1 &> /dev/null shift done fiCopy the code

Analysis: If there is no input parameter (the total number of parameters is 0), an error message is displayed and exit; Otherwise, enter the cycle; If the first parameter is not null, create a user with the name of the first parameter, remove the first parameter, and move the following parameter to the left as the first parameter, until there is no first parameter, exit.

Print the right triangle character #! /binbash while (($# > 0)) do echo "$*" shift doneCopy the code

Create an infinite loop

while true ; Do loop body doneCopy the code

4, loop can be parallel execution, make the script run faster

(1) Usage

For name in list; Do {loop body}& done waitCopy the code

(2) Examples:

Read -p "Please input network (eg:192.168.0.0): " 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])\>" [ $? -eq 0 ] || ( echo "input error"; Exit = 10) IP ` echo $net | egrep - o ^ "([0-9] {1, 3} \.) {3}"` for i in {1.. 254}; do { ping -c 1 -w 1 $IP$i &> /dev/null && \ echo "$IP$i is up" }& done waitCopy the code

Analysis: Enter an IP address 192.168.37.234. If the format is not 0.0.0.0, an error message is displayed. If yes, the IP variable is 192.168.37.I and the range is 1-254. Ping 192.168.37.1-154 simultaneously. If the ping succeeds, the IP address is displayed as UP. Until the loop ends.

4. Signal capture trap

1, Usage format

Trap 'trigger instruction' signal, the custom process will execute the trigger instruction after receiving the specified signal sent by the system, but will not execute the original operation trap '' signal, ignore the signal operation trap '-' signal, restore the original signal operation trap -p, and list the custom signal operationsCopy the code

Signal can be expressed in three ways: signal number 2, full name SIGINT, abbreviated INT

2. Common signals

1) SIGHUP: re-read configuration file without closing process 2) SIGINT: abort running process; Equivalent to Ctrl+ C 3) SIGQUIT: equivalent to Ctrl+ 9) SIGKILL: Force kill running process 15) SIGTERM: terminates running process (default: 15) 18) SIGCONT: continues running 19) SIGSTOP: background sleep 9 Signal, force kill, cannot captureCopy the code

3, case

Print 0-9, CTRL + C cannot terminate #! /bin/bash trap 'echo press ctrl+c' 2 for ((i=0; i<10; i++)); do sleep 1 echo $i doneCopy the code

Analysis: I =0, when I <10, every sleep 1 second, I +1, capture 2 signal, and echo press CTRL + C

Print 0-3, CTRL + C can not stop, 3 resume, can stop #! /bin/bash trap '' 2 trap -p for ((i=0; i<3; i++)); do sleep 1 echo $i done trap '-' SIGINT for ((i=3; i<10; i++)); do sleep 1 echo $i doneCopy the code

Analysis: I =0, when I <3, every sleep 1 second, I +1, capture 2 signals; When I >3, release signal 2.

Five, script knowledge

1, generate a random character cat /dev/urandom

# generate 8 random lowercase letters or Numbers cat/dev/urandom | tr - dc / : alnum: | head - 8 cCopy the code

2. Generate a RANDOM number echo $RANDOM

Echo $[$[RANDOM%7]+31 echo $[$[RANDOM%7]+31 echo $[[RANDOM%7]+31 echo $[$[RANDOM%7]+31Copy the code

3. Echo prints color words

Echo -e "\033[31malong\033[0m" along echo -e "\033[1; 31malong\033[0m" highlight red along echo -e "\033[41malong\033[0m" show red along echo -e "\033[31; 5malong\033[0m" displays flashing red along color=$[$[RANDOM%7]+31] echo -ne "\033[1;${color};5m*\033[0m" displays flashing RANDOM color alongCopy the code

Share a few interesting scripts

1. 9×9 times table

#! /bin/bash for a in {1.. 9}; do for b in `seq 1 $a`; do let c=$a*$b ; echo -e "${a}x${b}=$c\t\c" done echo doneCopy the code

2, color isosceles triangle

#! /bin/bash read -p "Please input a num: " num if [[ $num =~ [^0-9] ]]; then echo "input error" else for i in `seq 1 $num` ; do xing=$[2*$i-1] for j in `seq 1 $[$num-$i]`; do echo -ne " " done for k in `seq 1 $xing`; do color=$[$[RANDOM%7]+31] echo -ne "\033[1;${color};5m*\033[0m" done echo done fiCopy the code