bash - SHELL - IF 语句中的 AND 操作

标签 bash shell if-statement ksh

假设这些功能:

return_0() {
   return 0
}

return_1() {
   return 1
}

然后是下面的代码:

if return_0; then
   echo "we're in" # this will be displayed
fi

if return_1; then
   echo "we aren't" # this won't be displayed
fi

if return_0 -a return_1; then
   echo "and here we're in again" # will be displayed - Why ?
fi

为什么我进入最后一个 if 语句? 难道我们不应该使用那些 01 吗?

最佳答案

-atest命令的选项之一(也是[[[)。所以你不能单独使用 -a 。您可能想使用 &&,它是 AND 列表的控制运算符标记。

if return_0 && return_1; then ...

可以使用-a告诉test“和”两个不同的test表达式,比如

if test -r /file -a -x /file; then
    echo 'file is readable and executable'
fi

但这等同于

if [ -r /file -a -x /file ]; then ...

这可能更具可读性,因为括号使表达式的 test 部分更清晰。

有关...的更多信息,请参阅 Bash 引用手册

关于bash - SHELL - IF 语句中的 AND 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55729300/

相关文章:

delphi - 如何让程序在一条 if 语句中休眠两次?

linux - 对于第 2 列的唯一值,计算 linux 中第 11 列和第 17 列的所有对应值的平均值

linux - 使用 awk 和 bash 监视 exec 输出到日志

php - 用于删除整个目录中起始字符和结束字符之间的所有文本的 Shell 脚本或命令

linux - 如何使用具有文件列表的变量通过管道将输入发送到 tar

javascript - 注释中的条件运算符 floatval

java - 在 Java 中从命令行传递多个参数

ubuntu - 当我尝试在 .bashrc 中添加命令时找不到命令消息

linux - 如何检查目录 "d"是否存在但当前用户无权读取

c - 如何离开(中断)waitpid()函数?