条件 if
if condition
then
statements
else
statements
fi
列表序列 && ||
- &&
- 从左开始顺序执行每条命令
- 如果一条命令返回的是 True ,它右边的下一条命令才能够执行
- ||
- 如果一条命令返回的是 False,它右边的下一条命令才能够被执行
条件 case
- 多支路选择
- 每行指令,双 ;; 分隔
- 条件、指令,右括号 ) 分隔
case variable in
pattern [| pattern] ...) statements ;;
pattern [| pattern] ...) statements ;;
esac
#!/bin/sh
echo "Is it morning? Please answer yes or no"
read timeofday
case "$timeofday" in
yes | y ) echo "Good Morning";; # | y 可选条件 y
[nN]* ) echo "Good Afternoon";; # 所有 n 开头的都可以,用通配符*适配,不区分大小写
*) echo "Sorry , answer not recognized";;
esac
exit 0
循环 for while until
for variable in values # 遍历了values内所有元素,有几个元素就循环了几次
do
statements
done
while condition
do
statements
done
- until 不需要执行循环
- 循环将反复执行,直到(until)条件为真
- (while)在条件为真时,反复执行
- 如果需要循环至少执行一次,那么就使用 while 循环;
- 如果可能根本都不需要执行循环,就使用 until 循环。
# 设置一个警报,当某个特定的用户登录时,该警报就会启动,
# 通过命令行将用户名传递给脚本程序
#!/bin/bash
until who | grep "$1" >> ./output.txt # who - Linux内置系统命令,查看系统当前登陆用户
do
sleep 60
done
# now ring the bell and announce the expected user
echo -e '\a'
echo "**** $1 has just logged in ****"
exit 0