shell非常灵活,也是常用的脚本语言之一,最常用到的控制流语句也就是if,for,while,until。下面针对if语句使用中的一些注意事项
正常的shell语法
if 与then不在一行,如下:
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
if与then可以在一行,但要在条件后加上“;” 并且,分号与then之间有一空格,如下:
if condition1 ;then
command1
elif condition2 ;then
command2
else
commandN
fi
具体实例如下,if与then不在同一行:
#!/bin/bash
deployPlatform='2'
if [ $deployPlatform == '51' ]
then
echo "51测试环境"
elif [ $deployPlatform == '20' ]
then
echo "20开发环境"
else
echo "其他环境"
fi
可以使用在线运行环境,来验证执行结果
if与then在同一行实例如下:
#!/bin/bash
deployPlatform='2'
if [ $deployPlatform == '51' ]; then
echo "51测试环境"
elif [ $deployPlatform == '20' ]; then
echo "20开发环境"
else
echo "其他环境"
fi
执行结果:
注意,有几处需要空格的地方。
1、if 与【之间需要空格。
2、条件与【】之间需要空格。
3、if与then在同一行时,分号";"与 then之间需要空格