for 语句
for
do
done ###标准格式
for NUM in 1 2 3 ###循环从1到3
for NUM in {1..3} ###循环从1到3
for NUM in `seq 1 3` ###利用seq可以设置步长,步长为1
for NUM in `seq 1 2 10` ###步长为2
do
done
例 :写一个脚本,执行后显示1到3或显示1到10步长为2
vim test.sh
for NUM in `seq 1 3`
do
echo $NUM
done
while 语句
while 条件
do
done
例 :写一个脚本,执行后查询系统负载,并且每过1秒显示一次,在一行里
whlie true
do
echo `uptime`
echo "\r \r"
sleep 1
done
if 语句
if
then
elif
then
...
else
fi
例:写一个脚本,执行test.sh 后跟第一串字符为a,显示a,为b,显示b,为c,就显示c ,除过这三种情况都显示unknow
#!/bin/bash
if
[ "$1" = "a" ]
then
echo '$1' is a
elif
[ "$1" = "b" ]
then
echo '$1' is b
elif
[ "$1" = "c" ]
then
echo '$1' is c
else
echo unknow $1
fi
case 语句
case
word1 )
action1
;;
word2)
action2
;;
........
*)
action_last
esac
例:写一个脚本,运行 test1.sh dog 输出结果为 cat,运行 test1.sh cat 输出结果为 dog 除此以外都输出结果为 error
#!/bin/bash
case $1 in
dog)
echo cat
;;
cat)
echo dog
;;
*)
echo error
esac
expect
expect 是自动应答命令用于交互式命令的自动执行
spawn 是 expect 中的监控程序,其运行后会监控命令提出的交互问题
send 发送问题答案给交互命令
"\r" 表示回车
exp_continue 标示当问题不存在时继续回答下面的问题
expect eof 标示问题回答完毕退出 expect 环境
interact 标示问题回答完毕留在交互界面
set NAME [ lindex $argv n ] 定义变量
expect 示例
vim ask.sh ###写脚本
#!/bin/bash
read -p "what's your name: " NAME
read -p "How old are you: " AGE
read -p "Which class you study: " OBJ
read -p "You feel happy or terrible ?" FEEL
echo $NAME is $AGE's old and study $OBJ is feel $FEEL
chmod +x ask.sh ###给脚本执行权限
为避免交互式
yum install expect -y ###先安装expect
vim ask.exp
#!/usr/bin/expect
set timeout 2
set NAME [ lindex $argv 0 ] ###表示命令后跟第1串字符
set AGE [ lindex $argv 1 ] ###表示命令后跟第2串字符
set OBJ [ lindex $argv 2 ] ###表示命令后跟第3串字符
set FEEL [ lindex $argv 3 ] ###表示命令后跟第4串字符
spawn /mnt/ask.sh
expect {
name { send "$NAME\r";exp_continue } ###发送答案
old { send "$AGE\r";exp_continue }
study { send "$OBJ\r";exp_continue }
happy { send "$FEEL\r" }
}
expect eof
chmod +x /mnt/ask.exp
变量传出,先将.exp文件重命名为.sh
mv ask.exp answer.sh
#!/bin/bash
/usr/bin/expect <<EOF
spawn /mnt/ask.sh ###监控命令提出的交互问题
expect {
name { send "$1\r";exp_continue }
old { send "$2\r";exp_continue }
study { send "$3\r";exp_continue }
happy { send "$4\r" }
}
expect eof
EOF
再给权限chmod +x answer.sh
变量传递成功
脚本中的语句控制器
exit n ###脚本退出,退出值为 n
例:写一个脚本验证,当到数字3时循环所进行操作
#!/bin/bash
for NUM in {1..5}
do
if
["$NUM" -eq 3]
then
$1
fi
echo $NUM
done
echo hello world!!!
break ###退出当前循环
continue ###提前结束循环内部的命令,但不终止循环