条件判断语法

if 条件; then

  #条件成立执行的命令,可以有多个命令

else

  #条件不成立执行的命令,可以多个命令

fi

条件判断之字符串判断

$str1 == $str2 #字符串是否相等

$str1 != $str2 #字符串是否不相等

-z "$str" #字符串长度是否为0 zero

-n "$str" #字符串长度是否不为0   not zero

条件判断之字符串判断测试

[ "jackin" == "jackin" ]

echo $?

[ "jackin" == "jackin  " ]

echo $?

[ -z "jackin" ]

echo $?

字符串判断举例,建议变量要加双引号

myname="jackin"

if [ "$myname" == "jackin" ];then

  echo "my name is jackin"

else

  echo "my name is not jackin"

fi

变量不加双引号的话,可能会有语法错

if [ $myname == "jackin" ];then

  echo "your name is jackin"

else

  echo "your name is not jackin"

fi

判断rpm包是否已安装,升级有可能会导致系统问题

rpm -qa pcre-devel #返回值都为0,无法根据返回值判断

result=$(rpm -qa pcre-develaa) #使用$()获取命令的输出

echo $result

result=$(rpm -qa pcre-devel)

echo $result

softpack="pcre-devel"

soft_result=$(rpm -qa $softpack)

if [ -z "$soft_result" ];then

  echo "${softpack} is not find"

  yum install ${softpack} -y

else

  echo "${softpack} is find"

fi

Logo

华为云1024程序员节送福利,参与活动赢单人4000元礼包,更有热门技术干货免费学习

更多推荐