shell中的循环控制语句

for 语句

for NUM in 1 2 3 
for NUM in {1..3}   
for NUM in `seq 1 3` 或者 for NUM in `seq 1 2 10`
do
done

for 语句示例

for NAME in westos linux 666
do
    echo $NAME
done

输出:

 [root@localhost oo]# sh test.sh 
----westos----
----linux----
----666----
[root@localhost oo]# 

while 语句

while 条件
do
done

while 示例

while true
do
echo -n `uptime` 
echo -ne "\r \r" 
sleep 1
done

输出: 下面的时间是不停更新的图片上看不出
输出


if 语句

if
then
elif
then
。。。
else
fi

if 语句示例

if [ "$1" == "cat" ]
then
echo "this is cat!!"
elif [ "$1" == "dog" ]
then
echo "this is dog!!"
else
echo "error:please input cat or dog!!"
fi

输出:

[root@localhost oo]# sh test.sh ooo
error:please input cat or dog!!
[root@localhost oo]# sh test.sh cat
this is cat!!
[root@localhost oo]# sh test.sh dog
this is dog!!
[root@localhost oo]# 

case 语句

case和if语句类似,在执行上有差异,if执行时时串行执行的,从上向下执行,而case语句是并行的,每个分支是平等的。

case $word in
word1 )
action1
;;
word2)
action2
;;
*)
action_last
esac

case 语句示例

case $1 in  
westos)
echo linux
;;
linux)
echo westos
;;
*)
echo "Error: input westos or linux after script !!"
esac

输出:

[root@localhost oo]# sh test.sh oo
Error: input westos or linux after script !!
[root@localhost oo]# sh test.sh linux
westos
[root@localhost oo]# sh test.sh westos
linux
[root@localhost oo]# 

expect

expect 是自动应答命令用于交互式命令的自动执行
spawn 是 expect 中的监控程序,其运行后会监控命令提出的

交互问题

  • send

发送问题答案给交互命令

  • “\r”

表示回车

  • exp_continue

标示当问题不存在时继续回答下面的问题

  • expect eof

标示问题回答完毕退出 expect 环境

  • interact

标示问题回答完毕留在交互界面

  • set NAME [ lindex $argv n ]

定义变量

expect 示例

exoect 自动应答脚本
expect需要运行环境/usr/bin/expect
前提:
yum install expect-5.45-14.el7_1.x86_64 -y


expect 示例

ask.sh 需要应答的脚本

 #!/bin/bash
read -p "what's your name: " NAME
read -p "How old are you: " AGE
read -p "Which class you study: " CLASS
read -p "You feel happy or terrible ?" FEEL
echo $NAME is $AGE's old 
echo CLASS is  $CLASS
echo and $NAME is feel $FEEL

chmod +x ask.sh #添加可执行权限

test.sh #expect自动应答脚本

#!/bin/bash
/usr/bin/expect <<EOF |grep -v -E "what|How|Which|or"
spawn /root/Desktop/oo/ask.sh
expect {
"*name:" { send "lee\r" ; exp_continue}
"*old*" { send "18\r" ; exp_continue }
"*study:" { send "linux\r" ; exp_continue }
"*feel*" { send "happy\r"}
}
expect eof
EOF

输出: 运行脚本时都是脚本自动应答,没有手动输入

 [root@localhost oo]# sh test.sh 
spawn /root/Desktop/oo/ask.sh
lee is 18\'s old 
CLASS is  linux
and lee is feel happy
[root@localhost oo]# 

脚本中的语句控制器

学过编程的人都知道,这里就不多说了。

  • exit n 脚本退出,退出值为 n
  • break 退出当前循环
  • continue 提前结束循环内部的命令,但不终止循环
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值