@yanglt7
2018-10-30T12:33:09.000000Z
字数 2886
阅读 830
Shell
while 循环语句的基本语法为:
while <条件表达式>docmd...done
until <条件表达式>docmd...done
例 9-1 每隔 2 秒在屏幕上输出一次负载值。
#!/bin/bashwhile true #<== 表达条件永远为真,会一直运行,称之为守护进程。douptimesleep 2done
将负载值追加到 log 里,使用微秒单位
#!bin/bashwhile [ 1 ]douptime >>/tmp/uptime.logusleep 2000000done
通过在脚本的结尾使用 & 符号来在后台运行脚本
[root@web001 scripts]# sh 9_1.sh &[2] 15344[root@web001 scripts]# tail -f /tmp/uptime.log09:49:34 up 1 day, 7:25, 2 users, load average: 0.00, 0.01, 0.0509:49:36 up 1 day, 7:25, 2 users, load average: 0.00, 0.01, 0.0509:49:38 up 1 day, 7:25, 2 users, load average: 0.00, 0.01, 0.0509:49:40 up 1 day, 7:25, 2 users, load average: 0.00, 0.01, 0.05...
| usage | description |
|---|---|
| sh while1.sh & | 把脚本 while1.sh 放到后台执行 |
| ctrl+c | 停止执行当前脚本或任务 |
| ctrl+z | 暂停执行当前脚本或任务 |
| bg | 把当前脚本或任务放到后台执行,background |
| fg | 把当前脚本或任务放到前台执行,如果有多个任务,可以使用 fg 加任务编号调出对应的脚本任务,frontground |
| jobs | 查看当前执行的脚本任务 |
| kill | 关闭执行的脚本任务,即以 “ kill %任务编号 ” 的形式关闭脚本 |
[root@web001 scripts]# sh 194load.sh &[1] 16043[root@web001 scripts]# fgsh 194load.sh^Z[1]+ Stopped sh 194load.sh[root@web001 scripts]# bg[1]+ sh 194load.sh &[root@web001 scripts]# jobs[1]+ Running sh 194load.sh &[root@web001 scripts]# fg 1sh 194load.sh^C
使用 kill 命令关闭 jobs 任务脚本
[root@web001 scripts]# jobs[1]- Running sh 194load.sh &[2]+ Running sh 194load.sh &[root@web001 scripts]# kill %2[root@web001 scripts]# jobs[1]- Running sh 194load.sh &[2]+ Terminated sh 194load.sh
进程管理的Linux 相关命令:
例 9-2 使用 while 循环或 until 循环竖向打印 54321。
#!/bin/bashi=5#while ((i>0))#while [[ $i > 0 ]]#while [ $i -gt 0 ]until [[ i < 1 ]]doecho "$i"((i--))done
例 9-3 猜数字游戏。首先让系统随机生成一个数字,范围为(1-60),让用户输入所猜的数字。如果不符合要求,则给予或高或低的猜对后则给出猜对所用的次数。
#!/bin/bashcnt=0NUM=$((RANDOM%61))input(){read -p "pls input a num:" numexpr $num + 1 &>/dev/null[ $? -ne 0 ] && echo "pls input a 'num'."input}guess(){((cnt++))if [ $num -eq $NUM ]; thenecho "You are right."if [ $cnt - le 3 ]; thenecho "You have try $cnt times, excellent!"elif [ $cnt -gt 3 -a $cnt le 6 ]; thenecho "You have try $cnt times, good."elif [ $cnt -gt 6 ]; thenecho "You have try $cnt times."fiexit 0elif [ $num -gt $NUM ]; thenecho "It is too big. Try again."inputelif [ $num -lt $NUM ]; thenecho "It is too small. Try again."inputfi}main(){inputwhile truedoguessdone}
方式 1: 采用 exec 读取文件,然后进入 while 循环处理
exec <FILEsum=0while read linedocmddone
方式 2:使用 cat 读取文件内容,然后通过管道进入 while 循环处理
cat FILE_PATH|while read linedocmddone
方式 3:在 while 循环结尾 done 处输入重定向指定读取的文件。
while read linedocmddone<FILE
1)while 循环结构及相关语句综合实践小结
2)Shell 脚本中各个语句的使用场景