shell脚本简单例子

eg: 

Expect:

1.用环境变量RANDOM随机生成一个100以内的随机数

2.read读取当前输入

3.当前输入对比随机生成的数

4.当两个数相等时跳出苏循环,并计数(比较n次结果才相等)

 1 #!/bin/bash
 2 i=0
 3 num=$(expr $RANDOM % 100)
 4 echo $num
 5 while true
 6 do
 7         let i++
 8         read -p "Please input number(1-100):" digit
 9         if [ $digit -eq $num ]; then
10                 echo $digit
11                 echo "一共$i 次!!"
12                 break
13         elif [ $digit -lt $num ]; then
14                 echo "The number is less!"
15         elif [ $digit -gt $num -o $digit -gt 100 ]; then
16                 echo "The number is bigger"
17         #elif [ $digit -gt 100 ]; then
18         #       echo "not in the range!! Please reinput."
19         else
20                 continue
21         fi
22 done

eg: 

复习简单实例 ,    简单输入n次要取得值,最后打印出获得的所有值

 1 #!/bin/bash
 2 attr=()
 3 num=0
 4 while true
 5 do
 6         read -p ">>input:" name
 7         attr[$num]=$name
 8         echo ${attr[$num]}
 9         let num++
10         if [ $num -eq 3 ]; then
11                 echo ${attr[*]}
12                 exit
13         fi
14 done

eg:for循环

eg:continue和break的区别 

  continue结束本次循环,进行下一次循环

  break跳过本次循环

 1 #!/bin/bash
 2 for i in `seq 10`
 3 do
 4         if [ $i -eq 3 ]; then
 5                 continue
 6         else
 7                 echo $i
 8         fi
 9 done
10 
11 #!/bin/bash
12 int=0
13 while :
14 do
15         let int++
16         if [ $int -lt 10 ]; then
17                 echo $int
18         else
19                 break
20         fi
21 done
22 ====================
23 for循环的用法
24 #!/bin/bash
25 for ((a=1;a<10;a++))
26 do
27         echo $a
28 done
29 ====================
30 嵌套循环
31 #!/bin/bash
32 for ((a=0;a<10;a++))
33 do
34         echo "outer loop: $a"
35         for ((b=1;b<10;b++))
36         do
37                 if [ $b -eq 4 ]; then
38                         continue
39                 else
40                         echo "inner loop: $b"
41                 fi
42         done
43 done
44 ====================

 shell脚本编写添加用户,随机密码后五位

 1 #!/bin/bash
 2 for ((i=1;i<6;i++))
 3 do
 4         password=`openssl rand -hex 8 | cut -c1-5`
 5         echo "$password"
 6         cat /etc/passwd|grep -qa user$i
 7         if [ $? -eq 0 ]; then
 8                 echo "user${i} already"
 9                 continue
10         else
11                 useradd user$i;echo $a|passwd --stdin user$i
12         fi
13 done

 

posted @ 2019-11-30 10:41  Security  阅读(225)  评论(0编辑  收藏  举报