Shell script: if...else的用法

1 最简单的例子
#!/bin/bash

if [ 10 -lt 20 ]
then
    echo "aaa"
else
    echo "bbb"
fi

运行结果:

aaa

-lt 是 less than的缩写。

2 shell script 中 if...else 的语法
if 某一判断条件
then
    ...
elif 另一判断条件
then
    ...
else
    ...
fi

再看一个稍微复杂一点的例子:

#!/bin/bash

echo "Please enter your age:"
read age

if [ -z "$age" ]
then
        echo "Sorry, you didn't input."
elif [ "$age" -lt 20 ] || [ "$age" -ge 50 ]
then
        echo "Sorry, you are out of the age range."
elif [ "$age" -ge 20 ] && [ "$age" -lt 30 ]
then
        echo "You are in your 20s"
elif [ "$age" -ge 30 ] && [ "$age" -lt 40 ]
then
        echo "You are in your 30s"
elif [ "$age" -ge 40 ] && [ "$age" -lt 50 ]
then
        echo "You are in your 40s"
else
        echo "Sorry, please input a number."
fi

运行:

Please enter your age:
43
You are in your 40s
3 判断条件的写法

常用的判断条件有两种写法:

test 描述条件的表达式

or

[ 描述条件的表达式 ]

所以:

if [ -z "$age" ]

等于

if test -z "$age"

-z string 用于判断一个字符串的长度是否为0。

当我们想知道一个判断中的关键字,如 -z, -lt-n 的含义时,我们可以使用命令:

man test
...

       -n STRING
              the length of STRING is nonzero

       -z STRING
              the length of STRING is zero
...

如果我们想把 if 和 then 写在一行中,还可以这样写:

if [ -z "$age" ]
then

等于

if [ -z "$age" ]; then

最后,在Bash, Zsh and the Korn shell中,引入了一个功能更强大的关键字 [[ ]], 用来取代 [ ]。如果感兴趣,可以看这里:http://mywiki.wooledge.org/BashFAQ/031

还有一种写法:

# false && echo foo || echo bar
bar
# true || echo foo && echo bar
bar

其中&&为真时执行,||为假时执行。

参考文献

  1. Shell Command Language Specifications Issue 7
  2. test (Unix) wikipedia
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 基本上,shell script 有点像早期的批处理程序,即将一些命令汇整起来一次执行,但shell script...
    Zhang21阅读 4,905评论 0 0
  • 概述 首先,咱们来了解一下,什么是Shell。操作系统内核给我们提供了各种接口,同时也提供了各种用户层的库,理论上...
    keysaim阅读 5,281评论 0 0
  • 什么是Shell Shell应该是命令解释器,将Shell脚本解析成操作系统能理解的操作去执行。Shell脚本就是...
    乔伯阅读 7,218评论 2 8
  • 在前端工程化普及的今天,前端开发的同学几乎不可避免地要使用自动化脚本进行项目构建,而这些脚本基本上都通过 Shel...
    慢慢飞er阅读 8,046评论 2 14
  • 关于shell,一个广义的解释就是在用户与操作系统之间,提供一个工具或接口给用户来操作计算机系统;用户在shell...
    Sam_Lau阅读 24,770评论 13 126

友情链接更多精彩内容