场景描述
在写 Shell 脚本的时候,有时候会遇到比较复杂的逻辑判断,只有当这些的复杂的逻辑判断返回 true 或 false 时才执行某些操作,这时如果把这些复杂的逻辑判断直接写在 if 后面,会显得比较乱,可读性很差,而且后期不容易维护。
解决方法
对于上面描述的场景,我们可以把复杂的逻辑判断写到一个函数里,根据这些复杂逻辑判断的结果,我们希望这个函数能够返回 true 或 false。
但是,Bash 中并没有布尔类型的值,参考 bash 的 man 手册,函数中的 return 只能返回一个数值:
return [n]
...
The return status is non-zero if return is supplied a non-numeric argument, or is used outside a function and not during execution of a script by . or source.
...
man bash
不过,在 Shell 中,一个命令执行是否成功可以用它的 exit code 来判断,0 表示成功, 非 0 值来表示失败:
For the shell's purposes, a command which exits with a zero exit status has succeeded. An exit status of zero indicates success. A non-zero exit status indicates failure.
man bash
而函数中的 return 值,其实就是函数的退出状态,因此我们可以用 return 0 来表示 true, return 1 来表示 false。
示例
下面通过一个例子来说明,在这个例子中,我们判断一个给定的路径是否是一个目录:
#!/bin/bash
function isDir() {
path="$1"
if [ -d "$path" ]
then
# 0 表示 true
return 0
else
# 1 表示 false
return 1
fi
}
path="/tmp"
if isDir "$path"
then
echo "$path is dir"
else
echo "$path is not dir"
fi
在上面的例子中,我们将条件判断写到了 isDir() 函数中,但判断给定路径是目录时,返回 0 (true);否则返回 1 (false)。
众所周知,Linux 系统中 /tmp 是一个目录,因此上面程序的运行结果为:
/tmp is dir
当然,上面的例子比较简单,并没有必要使用函数,但是在遇到逻辑判断比较复杂的场景时,将逻辑判断写到函数里会是一个更好的方法。
总结
Shell 中并没有布尔类型,但是我们可以在函数中使用 return 0 表示返回 true;return 1 表示 false。在写 Shell 脚本时,将复杂的逻辑判断写到函数里,然后通过返回 0 或 1 来表示 true 或 false,会让 Shell 脚本可读性更强,后期维护起来也更方便。
扫描下面的二维码关注我的微信公众号: