Shell 快速入门(十二):选择结构怎么写

文章首发于【陈树义的博客园】,点击跳转到原文:https://www.cnblogs.com/chanshuyi/p/quick_start_of_shell_12_if_structure.html

与其他语言一样 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

posted @ 2020-11-01 11:47  陈树义  阅读(219)  评论(0编辑  收藏  举报