文章目录
1. for循环
for in
do //做什么动作
done
in后多少个变量,就循环几次
in:seq 1 2 10:设定步长为2,1 3 5 7 9
in:后也可以接运算的方式
测试题
- 检测10-20主机有哪些主机运行着,并显示172.25.254…is up
- 脚本执行:10秒的倒计时
#!/bin/bash
for SEC in {10..1}
do
echo -ne "\bAfter ${SEC}s is end \r"
sleep 1
done
2. 条件语句
2.1 while…do语句
作用:条件为真,执行动作
while ture //条件为真
do //条件成立,所循环的动作
done //结束
2.2 until…do语句
作用:条件为假,执行动作
until false //条件为假
do //条件不成立,所循坏的动作
done //结束
2.3 if语句
作用:多次判定条件,去执行动作
if //首次判断
then //条件成立,执行动作
elif //当首次判定不成立时,再次判定
then //条件成立时,执行动作
else //所有条件不成立时,执行动作
fi //结束
测试题
- 检测文件
sh check_file.sh
输出please input filename:file
file is not exist
file is exist
file is directory
此脚本会一直执行,直到用户输入exit
为止
3. case
case $1 in
word1|WORD1)
action1
;;
word2|WORD2)
action2
;;
*)
action3
esac
4. expect自动应答
问题脚本
#!/bin/bash
read -p "what is your name:" NAME
read -p "How old are you:" AGE
read -p "Which objective:" OBJ
read -p "Are you ok?" OK
echo $NAME is $AGE's old study $OBJ feel $OK
应答脚本
#!/usr/bin/expect
set timeout 1
set NAME [ lindex $argv 0 ]
set AGE [ lindex $argv 1 ]
set OBJ [ lindex $argv 2 ]
set FEEL [ lindex $argv 3 ]
spawn /mnt/ask.sh
expect{
"name" { send "$NAME\r";exp_continue }
"old" { send "$AGE\r";exp_continue }
"objective" {send"$OBJ\r";exp_continue }
"ok" { send"$FEEL\r" }
}
expect eof
5. continue
定义:终止当次循环,提前进入下一个循环
6. break
定义:终止当前所在语句所有动作,进入语句外的其他动作
7. exit
定义:脚本退出