一、for语句
作?为循环执?动作 for语句结构 for 定义变量 do 使?变量,执?动作 done 结束标志
for语句的基本格式
[root@ansible test]
for WESTOS in $(seq 1 2 10)
do
echo $WESTOS
done
[root@ansible test]
1
3
5
7
9
[root@ansible test]
1
3
5
7
9
[root@ansible test]
westos
linux
lee
[root@ansible test]
10
9
8
7
6
5
4
3
2
1
[root@ansible test]
0
1
2
3
4
5
6
7
8
9
练习
check_host.sh ?此脚本检测10台与您当前主机直连主机是否?络通常 如果?络通常请显?主机的ip列表
[root@ansible test]
for IP in 172.25.254.$(seq 1 10)
do
ping 172.25.254.$IP &> /dev/null && {
echo 172.25.254.$IP
}
done
二、条件语句
1.while…do语句
作? 条件为真执?动作
while ture
do
done
2.until…do 语句
作? 条件为假执?动作
until false
do
done
3.if语句
作? 多次判定条件执?动作
if
then
elif
then
...
else
fi
练习
check_file.sh please input filename: file file is not exist file is file file is direcory 此脚本会?直询问直到??输?exit为?
[root@ansible test]
while true
do
read -p "please input filename:" FILE
if [ $FILE = "exit" ]
then
echo bye!
exit
elif [ ! -e "$FILE" ]
then
echo $FILE is not exited!
elif [ -f "$FILE" ]
then
echo $FILE is a file!
elif [ -d "$FILE" ]
then
echo $FILE is a dir!
fi
done
三.case
if语句判定时,是从上到下判定的,假如判定有很多,恰好最后一个才符合条件,那么效率就比别人慢,这样很不合适。现在需要点名机制,case语句是效率一样。
基本结构
case $1 in
word1|WORD1)
action1
;;
word2|WORD2)action2
;;
*)
action3
esac
示例:
[root@ansible test]
case $1 in
haha)
echo haha
;;
westos)
echo westos
;;
*)
echo error
esac
四、expect
我们写脚本的目的就是为了自动执行,但是有些命令需要输入参数才可以执行,比如ssh远程连接时,会要求输入密码,输入成功才可以执行后面的操作,有时还需要先输入yes认证完再输入密码,那这种情况怎么办呢?就需要用到expect应答脚本。
问题脚本
[root@ansible test]
read -p "what's 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
[root@ansible test]# sh ask.sh
what's your name:1
How old are you: 1
Which objective: 1
Are you ok? 1
1 is 1's old study 1 feel 1
[root@ansible test]# /test/ask.sh <<EOF
> 2
> 2
> 2
> 2
> EOF
2 is 2's old study 2 feel 2
应答脚本
[root@ansible test]
set timeout 1
set NAME [ lindex $argv 0 ]
set AGE [ lindex $argv 1 ]
set OBJ [ lindex $argv 2 ]
set FEEL [ lindex $argv 3 ]
spawn /test/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
[root@ansible test]
spawn /test/ask.sh
what's your name:2
How old are you: 2
Which objective: 2
Are you ok? 2
2 is 2's old study 2 feel 2
转载解释很清楚的博客
五、break,continue,exit
contiue 终?当此次前循环提前进?下个循环
break 终?当前所在语句所有动作进?语句外的其他动作
exit 脚本退出
原本输出:
[root@ansible test]
for NUM in {1..10}
do
if [ "$SUM" = "4" ]
then
echo jiajiren is handsome
fi
echo $NUM
done
echo complete
exit break: continue:
|