Shell Programming case Multi-Branch Statement, Loop Statement (for, while, etc.), Shell Function, Shell Array

Keywords: Linux shell vim Apache DNS

case multi-branch statement

The structure of case statement:

Execute different command lines for different values of variables

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

Example:

Character type recognition:

  • Prompt the user to enter a character;
  • Judge that the character is a letter, number or other character.

The script is as follows:

[root@localhost opt]# vim test01.sh
#!/bin/bash
read -p "Please enter a character:" key
case $key in
[a-z]|[A-Z])
        echo "You enter letters."
;;
[0-9])
        echo "What you enter is a number."
;;
*)
        echo "You enter special symbols."
esac
The results are as follows:

[root@localhost opt]# chmod +x test01.sh 
[root@localhost opt]# ./test01.sh 
Please enter a character: 3
 What you enter is a number.
[root@localhost opt]# ./test01.sh 
Please enter a character: d
 You enter letters.
[root@localhost opt]# ./test01.sh 
Please enter a character:#
You enter special symbols.
[root@localhost opt]# 

Loop statement

for loop statement:

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

for variable name in value list
do
    Command sequence
done

Example 1:

Add users in batches:

  • User names are stored in users.txt files, one for each line.
  • The initial passwords are set to 123456.
  • Verify scripts.

The specific experiments are as follows:

[root@localhost opt]# tail -5 /etc/passwd
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
jiang:x:1000:1000:jiang:/home/jiang:/bin/bash
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
[root@localhost opt]# vim users.txt
[root@localhost opt]# cat users.txt 
zhangsan
lisi
wangwu
zhaoliu
[root@localhost opt]# vim test02.sh
[root@localhost opt]# The cat test02.sh//shell script is as follows
#!/bin/bash
TMP=$(cat /opt/users.txt)
for USER in $TMP
do
    useradd $USER && echo "123456" | passwd --stdin $USER &> /dev/null
done
[root@localhost opt]# chmod +x test02.sh 
[root@localhost opt]# ./test02.sh 
[root@localhost opt]# tail -5 /etc/passwd
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
zhangsan:x:1001:1001::/home/zhangsan:/bin/bash
lisi:x:1002:1002::/home/lisi:/bin/bash
wangwu:x:1003:1003::/home/wangwu:/bin/bash
zhaoliu: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 according to IP address:

  • The IP address is stored in the ipadds.txt file, one per line.
  • Use ping command to detect the connectivity of each host.

The shell script is as follows:

#!/bin/bash
TMP=$(cat /opt/ipadds.txt)
for USER in $TMP
do
 ping -c 3 -i 0.2 -w 3 $USER &> /dev/null
 if [ $? -eq 0 ]
 then
  echo "$USER is up"
 else
  echo "$USER is down"
 fi
done

The while loop statement:

Loop structure: Repeated testing of a condition, as long as the condition holds, repeated execution.

while conditional test operation
do
    Command sequence
done

Example 1:

Add users in batches:

  • User names begin with stu and are numbered numerically.
  • A total of 10 users were added, namely stu1, stu2, stu20.
  • The initial passwords are set to 123456.

The shell script is as follows:

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

Example 2:

Guess commodity prices:

  • Random number is obtained by variable RANDOM.
  • The user is prompted to guess and record the number of times, and quit the loop after guessing.

The shell script is as follows:

#!/bin/bash
TIMES=0
PRICE=$(expr $RANDOM % 1000)
while true
do
read -p "Please guess the price.(0-999): " money
let TIMES++
     if [ $money -gt $PRICE ]
     then 
         echo "You guessed too much."
     elif [ $money -lt $PRICE ]
     then       
         echo "Your guess is too small"
     else         
         echo "You guessed right. The correct price is: $num"
         echo "You guessed it altogether. $TIMES second"
     break 
     fi 
done 

until loop statement:

Loop structure: Repeated testing of a condition, as long as the condition is not established, repeated execution.

until conditional test operation
do
   Command sequence
done

Example 1:

Calculate the sum of 1 to 50:

  • The sum of 1-50 is calculated by cyclic accumulation.

The experiments are as follows:

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

Example 2:
Send online messages to specified users:

  • If the user is not online (not logged on to the system), try every 10 minutes until the user logs on to the system and sends information.
  • User names and messages are passed to scripts through location parameters.

The script is as follows:

#!/bin/bash
username=$1
#Judging Information Format
if [ $# -lt 1 ];then
        echo "Usage:`basename $0`<username> [<message>]"
        exit 1
fi
#Determine whether the user exists or not
if grep "^$username:" /etc/passwd > /dev/null
then :
else
        echo "user does not exist"
        exit 1
fi
#Whether the user is online or not, if not online, contact every 5 seconds
until who|grep "^$username" > /dev/null
do
        echo "Users are not online"
        sleep 5
done
mes=$*
echo $mes | write $username

Shell function

Shell function definition:

Writing command sequences together in format facilitates reuse of command sequences.

[function] function name (){
    Command sequence
        [return x]
}// Use return or exit to explicitly terminate functions

Method of calling function:

Function name [parameter 1] [parameter 2]

Example:

The sum of two numbers:

  • Define the function by sum () {};
  • Find the sum of two numbers by calling a function.

The experiments are as follows:

[root@localhost opt]# vim test06.sh 
[root@localhost opt]# cat test06.sh 
#!/bin/bash
sum(){
    s=`expr $1 + $2`
    echo $s 
}
[root@localhost opt]# chmod +x test06.sh 
[root@localhost opt]# ./test06.sh 
[root@localhost opt]# sum 5 6
11
[root@localhost opt]#

Shell array

Application scenarios include:

  • Get the length of the array
  • Get element length
  • Traversal element
  • Element slicing
  • Element substitution
  • Element deletion
    ......

Array definition method:

  • Method 1

Array name = (value 0 value 1 value 2.)

  • Method two

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

  • Method three
List name = "value 0 value 1 value 2..."
Array name = ($list name)
  • Method four
Array name [0]="value"
Array name [1]="value"
Array name [2]="value"

Array includes data types:

  • value type
  • Character Types: Definitions using "" or''

Gets the array length:

Format: ${#Array name [@*]}

//Example:
[root@localhost ~]# arr_ nymber=(1 2 3 4 5);
[root@localhost ~]#arr_ length=${#arr_ number[*]}
[root@localhost ~]# echo $arr length
5

Read the assignment of a subscript:

Format: ${array name [subscript]}

Example:
[root@localhost ~]#arr_ index2=${arr_ number[2]}
[root@localhost ~]# echo $arr_ index2
3

Array traversal:

[root@localhost ~]# for v in 
${arr_ number[@]}
> do
>     echo $V
> done
1
2
3
4
5

Shell script debugging

echo command

bash command

Syntax: sh [- nvx] script name

Common Options:

- n: No scripts are executed, just grammar checks. There are no grammar problems, no content is displayed, and there is a problem prompt to report an error.
- v: When executing a script, the content of the script is displayed first, and then the script is executed. When there is an error, give an error prompt.
- x: Output the executed script content to the screen.

set command

Set-x: Turn on adjustment mode
 set +x: Turn off the adjustment mode

Posted by merrydown on Sun, 13 Oct 2019 18:14:14 -0700