for语句
别写脚本打印1-10
编写脚本查看相同局域网内的1-10号ip是否工作并输出可以工作的ip
#!/bin/bash
for i in 172.25.254.{1…10}
do
ping -w1 KaTeX parse error: Expected 'EOF', got '&' at position 3: i &̲>/dev/null && e…i is up"
done
while语句
格式
while 条件
do
done
eg:
#!/bin/bash
while true
do
read -p “please input word :” word
$word
done
编写脚本,每过10s输出一次系统占用率
#!/bin/bash
while true
do
uptime
sleep 10
done
执行脚本
if语句
if 条件
then
elif 条件
then
elif 条件
then
else(若不加else,则不符合条件的命令不执行)
fi
case语句
expect语句
expect是自动应答命令
使用expect实现ssh连接
yum install expect -y下载ecpect插件
#!/usr/bin/expect
set IP [ lindex $argv 0 ] 变量ip
set PASS [ lindex $argv 1 ] 变量密码
spawn ssh root@$IP
expect {
"yes/no" { send "yes\r" ; exp_continue } 选择yes确认进行连接
"password" { send "$PASS\r" } 输入密码
}
interact
expect answer.exp 172.25.254.241 redhat连接172.25.254.241主机
如何使得shell环境中调用expect(输入重定向)
打印同一个网段中主机1到主机10可以工作的主机名。
#!/bin/bash
Auto()
{
/usr/bin/expect <<-EOF
spawn ssh root@$1 hostname
expect {
"yes/no" { send "yes\r" ; exp_continue }
"password" { send "westos\r"}
}
expect eof
EOF
}
for IP in {1..10}
do
ping -w1 172.25.254.$IP &> /dev/null
if [ "$?" = "0" ]
then
Auto 172.25.254.$IP | tail -n 1
fi
done
输出结果:
exit,break,continue
exit 直接退出脚本
break 退出当前循环
continue 提前结束循环内部的命令,但不终止循环
原脚本
#!/bin/bash
for i in {1..6}
do
if [ "$i" = "3" ]
then
echo lucky
fi
echo $i
done
echo end
源代码执行效果
exit
#!/bin/bash
for i in {1..6}
do
if [ "$i" = "3" ]
then echo lucky
exit 执行exit命令退出
fi
echo $i
done
echo end
exit执行结果
直接结束了程序,end也没有打印
break
#!/bin/bash
for i in {1..6}
do
if [ "$i" = "3" ]
then echo lucky
break break退出循环
fi
echo $i
done
echo end
退出了for循环,但依旧会打印end
continue
#!/bin/bash
for i in {1..6}
do
if [ "$i" = "3" ]
then
echo lucky
continue continue断开当前命令
fi
echo $i
done
echo end
执行效果
不会打印3的输出