1、条件语句
1、单分支 if 语句
if conditionthencommand1command2...commandNfi# 判断nginx服务是否启动: grep -v 排除grep命令,if [ $(ps aux | grep nginx | grep -v grep | wc -l) -ge 1 ];thenecho "nginx server exist!"fi
2、多分支 if 语句if condition1;thencommand1elif condition2;thencommand2......elif conditionN;thencommandNelsecommandfi
# 获取系统版本信息sys_version=$(rpm -q centos-release | cut -d- -f3)if [ ${sys_version} -eq 6 ];thenecho "sysversion is ${sys_version}"elif [ ${sys_version} -eq 7 ];thenecho "sysversion is ${sys_version}"elseecho "sysversion is ${sys_version}"fi
2、循环语句
1、for 循环:
循环列表以 $IFS 分割,默认为空白符。可自定义修改。for 循环语法:
for var in item1 item2 ... itemNdocommand1command2...commandNdone
# 求1~10的和sum=0for num in {1..10}dolet sum=${sum}+${num}doneecho "1~10的和为 ${sum}"
OLD_IFS=$IFS # 默认$IFS分隔符IFS=":" # 指定新的$IFS分隔符for i in $(head -1 /etc/passwd);doecho ${i}doneIFS=${OLD_IFS} # 还原$IFS分隔符
2、while循环:
while 循环通常用于处理未知数量对象的操作
while 条件表达式:docommanddone
p=$1 # 输入的第一个参数作为结束边界i=1 # 开始边界值sum=0 # 总和while [ ${i} -le ${p} ]dosum=$(( ${sum}+${i} ))i=$(( ${i}+1 ))doneecho "1~${stop}的和是:${sum}"
3、until循环
条件表达式为 true 时停止,否则一直运行
until 条件表达式docommanddone
# 打印 1-5 数字NUM=0until [ ${NUM} -ge 5 ]dolet NUM++echo $NUMdone
4、break与continue
#!/bin/bash
N=0
while true; do
let N++
if [ $N -eq 5 ]; then
break
fi
echo $N
done
#!/bin/bash
N=0
while [ $N -lt 5 ]; do
let N++
if [ $N -eq 3 ]; then
continue
fi
echo $N
done
3、选择语句
1、case语句
case 模式名 in
模式 1)
命令
;;
模式 2)
命令
;;
*)
不符合以上模式执行的命令
esac
# 匹配输入的参数与对应的命令
case $1 in
start)
echo "start..."
;;
stop)
echo "stop..."
;;
restart)
echo "restart..."
;;
*)
echo "command not in {start|stop|restart}"
esac
