目录
1.for语句
2.条件语句
while...do语句
until...do 语句
if...then...elif...then...else...fi 语句
3.case语句
4.expect
5.break,continue,exit
1.for语句
作用:为循环执行动作
for语句结构
for //定义变量
do //使用变量,执行动作
done //结束标志
for语句的基本格式
格式1:
for WESTOS in `seq 2 2 10`
do
echo $WESTOS
done
格式2:
for WESTOS in 1 2 3
do
echo $WESTOS
done
格式3:
for WESTOS in {10..1}
do
echo $WESTOS
done
格式4:
for ((WESTOS=0;WESTOS<10;WESTOS++))
do
echo $WESTOS
done
练习
check_host.sh
用此脚本检测
10
台与您当前主机直连主机是否网络通常
如果网络通常请显示主机的
ip
列表
for name in 10 20 30
do
ping -c1 -w1 192.168.81.$name &> /dev/null && echo 192.168.81.$name is up ||echo 192.168.81.$name is down
done
2.条件语句
while...do语句
作用
: 条件为真执行动作
语句结构
while ture //条件为真
do //条件成立所做循环动作
done //会一直判断循环
until...do 语句
作用
: 条件为假执行动
语句结构
until false //条件为假
do //条件不成立所做循环动作
done
if...then...elif...then...else...fi 语句
作用:多次判定条件执行动作
代码结构
if //首次判断定
then //条件成立执行动作
elif //当首次判定不成立时再次判定
then //条件成立执行动作
... //elif可以书写多次
else //所有条件不成立执行动作
fi // 结束
脚本练习:
check_file.sh
please input filename: file
file is not exist
file is file
file is direcory
此脚本会一直询问直到用户输入
exit
为止
while true
read -p "please input filename: " FILENAME
do
if [ "$FILENAME" = "exit" ]
then
echo exit
exit
elif [ ! -e "$FILENAME" ]
then
echo $FILENAME is not exist
elif [ -f "$FILENAME" ]
then
echo $FILENAME is file
elif [ -d "$FILENAME" ]
then
echo $FILENAME is directory
fi
done
3.case语句
执行效率更高
case $1 in
word1|WORD1)
action1
;;
word2|WORD2)
action2
;;
*)
echo error
esac
4.expect
需安装expect
问题脚本
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
应答脚本
#!/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 sh /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
将expect该为shell
#!/bin/bash
expect(){
/usr/bin/expect <<EOF
spawn $5
expect {
"name" { send "$1\r";exp_continue }
"old" { send "$2\r";exp_continue }
"objective" { send "$3\r";exp_continue }
"ok" { send "$4\r" }
}
expect eof
EOF
}
expect su 12 shell ok "sh /mnt/ask.sh"
脚本练习
host_list.sh
检测
172.25.254.1-172.25.254.10 网络是否开启
如果网络正常生成解析列表
hosts_list
格式如下
ip 主机名称
例如
:172.25.254.1为开启状态主机名为westos_student1.westos.org
Auto_Ssh()
{
/usr/bin/expect <<EOF
spawn ssh -l root $1 hostname
expect {
"yes/no" {send "yes\r";exp_continue}
"password:" {send "westos\r"}
}
expect eof
EOF
}
[ -z "$1" ] && {
echo "Please input check ipaddress !!"
exit
}
ping -c1 -w1 $1 &> /dev/null && {
Auto_Ssh $1 | tail -n 1
} || {
echo $1 is down
}
读取一个用户列表文件,逐行创建用户,并在创建成功后输出提示信息。
if [ -z "$1" ]
then
echo please input userlist following $0
elif [ ! -e "$1" ]
then
echo $1 is not exist
else
for name in `cat $1`
do
useradd $name && echo $name is createed
done
fi
5.break,continue,exit
contiue ##终止当此次前循环提前进入下个循环
break ##终止当前所在语句所有动作进行语句外的其他动作
exit ##脚本退出