与其他语言一样 Shell 也有 IF-ELSE 以及 IF-ELSE-IF-ELSE 的选择结构。

IF ELSE 结构

Shell 语言中的 IF - ELSE 选择结构语法格式如下:

if condition
then
    command1 
    command2
    ...
    commandN
else
    command
fi

例如:

a=10
b=10
if [ $a = $b ]
then
  echo "a equals b"	# 输出这里
fi

IF ELSE-IF ELSE 结构

Shell 语言中的 IF ELSE-IF ELSE 结构语法格式如下:

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

例如:

a=9 
if [ $a = 10 ]
then
  echo "a == 10"
elif [ $a -lt 10 ]
then
  echo "a < 10"	# 输出这里
else 
  echo "a > 10"
fi

特别需要注意的是 if 后面的表达式,其左右两边都要留有一个空格,这是 Shell 的语法。如果没有空格,那么 Shell 执行的时候会报错。例如下面的 Shell 就会报错:

a=10 
if [$a = 10 ]
then
  echo "a is $a"
fi

执行之后,输出错误:-bash: [9: command not found。出错原因就是因为在 if 后面的表达式$a前面少了一个空格。

https://www.cnblogs.com/chanshuyi/p/quick_start_of_shell_12_if_structure.html

相关文章:

  • 2022-12-23
  • 2021-09-12
  • 2022-12-23
  • 2022-12-23
  • 2021-06-05
  • 2022-02-18
  • 2021-08-24
猜你喜欢
  • 2021-10-02
  • 2021-09-24
  • 2021-05-31
  • 2022-12-23
  • 2022-02-24
  • 2022-02-19
  • 2022-02-28
相关资源
相似解决方案