shell中常用的控制语句和脚本运行控制

一、语句
1、for语句
 for NUM in 1 2 3 					
 for NUM in {1..3} 								
 for NUM in `seq 1 3`  					前3个都是从1到3循环
 for NUM in `seq 1 2 10` 				从1到10,步长为2
 for NAME in westos linux 666	 
 for ((i=0;i<10;i++))
 for NAME in westos linux 666 			字符串的循环
 do
 done
2、while语句
while 条件 
do 
done
3、if语句
if 条件
then
	要执行的命令
elif 条件
then
	要执行的命令
...

else
	上边条件都不成立时执行的操作
fi	结束
4、case语句
case $1 in 
		westos|Westos|WESTOS)
		要执行的命令
		;;
		linux|LINUX|Linux)
		要执行的命令
		;;
		*)
		要执行的命令
esac
5、expect语句
yum install expect 			下载软件
expect 是自动应答命令用于交互式命令的自动执行 
spawn 是 expect 中的监控程序,其运行后会监控命令提出的 交互问题 
send 发送问题答案给交互命令 
"\r" 表示回车
exp_continue 标示当问题不存在时继续回答下面的问题 
expect eof 标示问题回答完毕退出 expect 环境 
interact 标示问题回答完毕留在交互界面 
set NAME [ lindex $argv n ] 定义变量

方法一:
<提问:>

vim ask.sh
	#!/bin/bash								  
	read -p "what's your name:" NAME	
	read -p "how old are:" AGE
	read -p "whice object you study:" OBJ
	read -p "are you happy:" FEEL
	echo $NAME is $AGE\'s old study $OBJ feel $FEEL

<应答:>

vim answer.exp
	#!/bin/exp
	spawn sh ask.sh			这里调用ask.sh
	expect "name"			搜索name关键字
	send "guo\r"			提交应答
	expect "old"
	send "32\r"
	expect "object"
	send "linux\r"
	expect "happy"
	send "happy"
	interact				保持
	#expect eof				结束	

<结果:>
interace 回车之后有结果
在这里插入图片描述
expect eof 回车之后不会有结果
在这里插入图片描述
方法二:
<提问>提问和方法一保持一致
<应答>

vim answer.exp
#!/bin/expect
	set timeout 5
	set NAME [ lindex $argv 0 ]
	set AGE [ lindex $argv 1 ]
	set OBJ [ lindex $argv 2 ]
	set FEEL [ lindex $argv 3 ]
	spawn sh ask.sh
	expect {
	        "name" { send "$NAME\r";exp_continue}
	        "old" { send "$AGE\r";exp_continue}
	        "object" { send "$OBJ\r";exp_continue}
	        "happy" { send "$FEEL\r"}
	}
	expect eof

<测试>e

expect answer.exp lee 21 linux happy

<结果>
在这里插入图片描述

二、语句控制

exit n 脚本退出,退出值为 n
break 退出当前循环
continue 提前结束循环内部的命令,但不终止循环

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值