一、语句
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 提前结束循环内部的命令,但不终止循环