一:for语句
与其他语言类似,shell中也支持for循环语句.
格式:
for 变量 in 列表
do
command1
command2
...
commandN
done
列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。
in 列表是可选的,如果不用它,for 循环使用命令行的位置参数
例如,1:输出当前列表中的字符串:
for NAME in westos linux 666
do
echo $NAME
done
2:显示主目录下以.bash开头的文件
#!/bin/bash
for FILE in $HOME/.bash*
do
echo $FILE
done
二:while语句
while 条件
do
done
1:while最常见的一个作用就是while true ,可以借助这个命令达到死循环的作用,将命令永远的执行下去
举例:
while true
do
echo -n `uptime` > /dev/$Dev_tty
echo -ne "\r \r" >/dev/$Dev_tty
sleep 2
done
三:if语句
if
then
elif
then
。。。
else
fi
举例:判断文件类型的脚本
vim test.sh
#!/bin/bash
if [ -z "$1" ];then
echo "please input file after command!!!"
else
{
if [ -e "$1" ];then
{
if [ -L "$1" ];then
echo "$1 is a link file"
elif [ -S "$1" ];then
echo "$1 is a socket file"
elif [ -b "$1" ];then
echo "$1 is a block file"
elif [ -d "$1" ];then
echo "$1 is a directory file"
elif [ -f "$1" ];then
echo "$1 is a comman file"
fi
}
else
echo "$1 is not exist!!!"
fi
}
四:case 语句
case
word1 )
action1
;;
word2)
action2
;;
........
*)
action_last
esac
#####case语句中执行的动作使同时进行的,同时判断,所以执行效率更高
举例:脚本实现服务的控制
#!/bin/bash
case $1 in
start)
systemctl $1 $2
;;
status)
systemctl $1 $2
;;
stop)
systemctl $1 $2
;;
restart)
systemctl $1 $2
;;
*)
echo error
esac
五:expectexpect 是自动应答命令用于交互式命令的自动执行
spawn 是 expect 中的监控程序,其运行后会监控命令提出的交互问题
send发送问题答案给交互命令
"\r"表示回车
exp_continue 标示当问题不存在时继续回答下面的问题
expect eof 标示问题回答完毕退出 expect 环境
interact标示问题回答完毕留在交互界面
set NAME [ lindex $argv n ] 定义变量
举例:统计当前网段主机的hostname
#!/bin/bash
SCRIPT()
{
/usr/bin/expect <<EOF
set timeout 10
spawn ssh root@$1 hostname
expect {
"yes/no" { send "yes\r";exp_continue }
"password" { send "$PASSWD\r" }
}
expect eof
EOF
}
for i in `seq 1 254`
do
ping -w1 -c1 172.25.254.$i &>/dev/null &&{
SCRIPT 172.25.254.$i |grep -E "spawn|password|Permanently|connecting|Permission" -v
}
done