if < 条件表达式 >
then
指令
fi
或者
if < 条件表达式 >;then
指令
fi
if < 条件表达式 >
then
指令1
else
指令2
fi
if < 条件表达式1 >
then
指令1
elif < 条件表达式2 >
then
指令2
elif < 条件表达式3 >
then
指令3
else
指令4
fi
条件表达式可以是test、[]、[[]]、(())等,也可以直接使用命令作为条件表达式 每个if语句都以if开头,并带有then,最后以fi结尾 多分支每个elif后也要带then,但else后不带then
符号条件表达式能够转换为if语句,如下
[ -f /etc/passwd ] && echo 1 || echo 0
等同于
if [ -f /etc/passwd ]
then
echo 1
else
echo 0
fi
其他条件表达式类似
case "变量" in
值1)
指令1...
;;
值2)
指令2...
;;
*)
指令3...
esac
说明:
;;
后停止,然后跳出case语句,执行case语句后面的其他指令*)
后面的指令,该指令通常是提示用户的指令,最后一个值可以省略双分号根据用户输入判断用户输入的哪个数值,并输出,如果非数值,则提示错误
cat /server/scripts/b7.sh
#!/bin/bash
read -p "pls input num[1-9]" num
case "$num" in
1)
echo "the num is 1"
;;
2)
echo "the num is 2"
;;
[3-9])
echo "the num is $num"
;;
*)
echo "pls input num,3q"
esac
执行脚本查看结果:
sh /server/scripts/b7.sh
pls input num[1-9]1
the num is 1sh /server/scripts/b7.sh
pls input num[1-9]3
the num is 3sh /server/scripts/b7.sh
pls input num[1-9]g
pls input num,3q原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。