我本质上是在尝试实现一个函数,该函数断言另一个命令的失败(非零退出代码),并在失败时打印一条消息。

这是我的功能:

function assert_fail () {
    COMMAND=$@
    if [ `$COMMAND; echo $?` -ne 0 ]; then
        echo "$COMMAND failed as expected."
    else
        echo "$COMMAND didn't fail"
    fi
}

# This works as expected
assert_fail rm nonexistent

# This works too
assert_fail rm nonexistent nonexistent2

# This one doesn't work
assert_fail rm -f nonexixtent

我在命令中添加选项后,该命令将不起作用。这是上面的输出:
rm: cannot remove `nonexistent': No such file or directory
rm nonexistent failed as expected.
rm: cannot remove `nonexistent': No such file or directory
rm: cannot remove `nonexistent2': No such file or directory
rm nonexistent nonexistent2 failed as expected.
rm -f nonexistent didn't fail

我曾尝试在命令周围加上双引号,但无济于事。我希望上面的第三次调用会产生与其他两次相似的输出。

我感谢任何/所有帮助!

最佳答案

rm -f 永远不会在不存在的文件上失败。它与您的包装器无关。见 man rm :

OPTIONS
       -f, --force
              ignore nonexistent files, never prompt

关于bash:将整个命令(带参数)传递给函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12898998/

10-13 03:20