Shell Programming case multiple branch statement, a loop statement (for, while, etc.), Shell function, array Shell

case multi-branch statement

case statement structure:

For different values ​​of variables, performs different command line

case  变量值  in
模式1)
    命令序列1
        ;;
模式2)
    命令序列2
    ;;
.....
*)
默认命令序列
esac

Shell Programming case multiple branch statement, a loop statement (for, while, etc.), Shell function, array Shell

Example :

Character type identification:

  • It prompts the user to enter a character;
  • It determined that the characters are letters, numbers or other characters.

Script is as follows:

[root@localhost opt]# vim test01.sh
#!/bin/bash
read -p "请输入一个字符:" key
case $key in
[a-z]|[A-Z])
        echo "你输入的是字母"
;;
[0-9])
        echo "你输入的是数字"
;;
*)
        echo "你输入的是特殊符号"
esac
执行结果如下:

[root@localhost opt]# chmod +x test01.sh 
[root@localhost opt]# ./test01.sh 
请输入一个字符:3
你输入的是数字
[root@localhost opt]# ./test01.sh 
请输入一个字符:d
你输入的是字母
[root@localhost opt]# ./test01.sh 
请输入一个字符:#
你输入的是特殊符号
[root@localhost opt]# 

loop statement

for loop:

Loop structure : reading a different variable values for the same set of commands executed one by one.

for  变量名  in  取值列表
do
    命令序列
done

Shell Programming case multiple branch statement, a loop statement (for, while, etc.), Shell function, array Shell

Example 1 :

Add users in bulk:

  • Users.txt user name stored in the file, one per line;
  • The initial passwords are set to 123456;
  • Validation script.

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]# cat test02.sh                                         //shell脚本如下
#!/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
密码:
[lisi@localhost opt]$

Example 2 :

According to the IP address of the host to check the status:

  • Ipadds.txt IP address is stored in a file, one per line;
  • Ping command to check the connectivity of each host.

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

while loop:

Cycle structure : a repeat test conditions, as long as the condition is true then repeatedly executed.

while  条件测试操作
do
    命令序列
done

Shell Programming case multiple branch statement, a loop statement (for, while, etc.), Shell function, array Shell

Example 1 :

Add users in bulk:

  • User name begins stu, numbered in numerical order;
  • Add a total of 10 users, namely stu1, stu2, .... stu20;
  • The initial passwords are set to 123456.

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 Price:

  • RANDOM random number obtained by variable;
  • And prompts the user to guess the number of records, after exiting the loop guess.

shell script is as follows:

#!/bin/bash
TIMES=0
PRICE=$(expr $RANDOM % 1000)
while true
do
read -p "请猜价格(0-999):" money
let TIMES++
     if [ $money -gt $PRICE ]
     then 
         echo "您猜的太大"
     elif [ $money -lt $PRICE ]
     then       
         echo "您猜的太小"
     else         
         echo "您猜对了,正确价格为:$num"
         echo "您一共猜了$TIMES次"
     break 
     fi 
done 

until loop:

Cycle structure : a repeat test conditions, as long as the condition is not satisfied then repeatedly executed.

until  条件测试操作
do
   命令序列
done

Shell Programming case multiple branch statement, a loop statement (for, while, etc.), Shell function, array Shell

Example 1 :

And calculating the value of 1 to 50:

  • 1 to 50 and the value calculated by the accumulated cyclic manner.

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 a message to the specified user line:

  • If the user is not online (unregistered system), the test once every 10 minutes, until the user logs in the system transmit information;
  • User name and message to the script by position parameters.

Script is as follows:

#!/bin/bash
username=$1
#判断信息格式
if [ $# -lt 1 ];then
        echo "Usage:`basename $0`<username> [<message>]"
        exit 1
fi
#判断用户是否存在
if grep "^$username:" /etc/passwd > /dev/null
then :
else
        echo "用户不存在"
        exit 1
fi
#用户是否在线,如果不在线每5秒联系一次
until who|grep "^$username" > /dev/null
do
        echo "用户不在线"
        sleep 5
done
mes=$*
echo $mes | write $username

Shell function

Shell function definition:

The command sequence written by format with a command sequence can be easily reused.

[ function ] 函数名(){
    命令序列
        [return x]
}                                              //使用return或exit可以显式地结束函数

Calling a function method:

Function name [Parameter 1] [parameter 2]

Example :

Sum of two numbers:

  • By sum () {} function is defined;
  • And find two numbers by calling the function.

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:

  • Gets an array of length
  • Gets the element length
  • Traversing element
  • Slice elements
  • Replace element
  • Remove elements
    ......

Array definition Methods:

  • method one

数组名= (value0 value1 value2 ..)

  • Method Two

数组名= ([0]=value [1]=value [2]=value ...) //数组元素之间使用空格隔开

  • Method Three
列表名="value0 value1 value2 ..."
数组名= ($列表名)
  • Method Four
数组名[0]="value”
数组名[1]="value"
数组名[2]="value"

An array of data types include:

  • Numeric types
  • Character type: using the definition of "" or ''

Gets an array of length:

格式:${#数组名[@\*]}

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

Under the subject of a reading assignment:

格式:${数组名[下标]}

实例:
[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:不执行脚本,仅检查语法。没有语法问题不显示任何内容,有问题提示报错。
-v:执行脚本时,先显示脚本内容,然后执行脚本。存在错误时,给出错误提示。
-x:将执行的脚本内容输出到屏幕上。

set command

set -x:开启调节模式
set +x:关闭调节模式

Guess you like

Origin blog.51cto.com/14449541/2442158