Bash“严格”模式和箭头(>)运算符

时间:2017-02-24 00:40:39

标签: bash io-redirection

以下是myscript.sh的内容:

#!/bin/bash
set -euo pipefail

# bar is an unexisting command
bar > test

当我调用./myscript.sh时,我收到以下错误消息(预期),

./myscript.sh: line 5: bar: command not found

但是创建了一个空的test文件:

-rw-r--r--    1 spg  staff     0B 23 Feb 16:32 test

我认为通过激活“严格”模式(使用set -euo pipefail的组合),找不到bar命令的失败将在此时停止脚本执行,而不是继续创建空test个文件。

如果test运算符左侧的表达式(在本例中为>)失败,我想知道如何阻止bar文件的创建。

1 个答案:

答案 0 :(得分:2)

重定向在调用进程之前完成,以便它的stdout(在本例中)可以连接到文件。这就是即使test不存在也会创建bar的原因。它不知道在设置重定向时调用命令会失败。

我认为在使用重定向时避免创建文件有一种直接的方法。您可以尝试先测试bar是否会成功,比如说

if command -v bar; then
    bar > test
else
    exit 1 # or whatever you want since the command would have failed
fi
相关问题