加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

shell训练day8 8.22

发布时间:2020-12-16 01:43:01 所属栏目:安全 来源:网络整理
导读:while循环 ? 语法 while 条件; do … ; done ? 案例1 #!/bin/bash while : do load= w|head -1|awk -F ‘load average: ‘ ‘{print $2}‘|cut -d. -f1 if [ $load -gt 10 ] then top|mail -s "load is high: $load" [email?protected] fi sleep 30 done :
while循环

? 语法 while 条件; do … ; done
? 案例1
#!/bin/bash
while :
do
load=w|head -1|awk -F ‘load average: ‘ ‘{print $2}‘|cut -d. -f1
if [ $load -gt 10 ]
then
top|mail -s "load is high: $load" [email?protected]
fi
sleep 30
done

: 的意思就是 死循环,也可以写成1或者true

获取负载

[[email?protected] ~]# uptime|awk -F ‘load average: ‘ ‘{print $2}‘|cut -d . -f 1
0--指定分隔符时多包含了空格
[[email?protected] ~]# uptime|awk -F ‘load average:‘ ‘{print $2}‘|cut -d . -f 1
0 返回多了空格多了空格

[[email?protected] whiletest]# cat load.sh
#!/bin/bash
while :
do
load=w|head -1|awk -F ‘load average: ‘ ‘{print $2}‘|cut -d. -f1
if [ $load -gt 10 ]
then
top|echo "load is high: $load"
fi
sleep 30
done

#!/bin/bash
while :
do
read -p "Please input a number: " n
if [ -z "$n" ]
then
echo "you need input sth."
continue
fi
n1=echo $n|sed ‘s/[0-9]//g‘
if [ -n "$n1" ]
then
echo "you just only input numbers."
continue
fi
break
done
echo $n

continue--表示继续上面的循环

n1=echo $n|sed ‘s/[0-9]//g‘ 表示一个纯数字变量

break 也可以用在for循环里

跳出循环
#!/bin/bash
for i in seq 1 5
do
echo $i
if [ $i == 3 ]
then
break
fi
echo $i
done
echo aaaaaaa

== 比较字符串,数字一般是用eq

为什么都是2次输出呢? --do后第一个echo打印了一个1,然后判断不等于3,fi后面又打印了一次

continue的用法
结束本次循环

#!/bin/bash
for i in seq 1 5
do
echo $i
if [ $i == 3 ]
then
continue
fi
echo $i
done
echo $i

continue就是 继续执行,而break就是重头再来

exit

#!/bin/bash
for i in seq 1 5doecho $iif [ $i == 3 ]thenexitfiecho $idoneecho aaaaaaa

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读