我实际上是在尝试实现一个函数,该函数断言另一个命令的失败(非零退出代码),并在失败时打印一条消息。
这是我的功能:
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
我尝试在命令周围加上双引号,但无济于事。我希望上面的第三次调用产生与其他两个类似的输出。
我感谢任何/所有帮助!