bash: 在代码块的条件下或在代码块的末尾重定向标准输入有什么区别?

bash: what is the difference between redirecting stdin in the condition of a code block or at its end?

在代码块语句中添加重定向和在代码块语句末尾添加重定向有什么区别吗?

例如,有什么区别:

if cat <<< foo; then
    code ...
fi

和:

if cat; then
    code ...
fi <<< foo

?

提前致谢

这里:

if cat; then
    code ...
fi <<< foo

...针对整个块 修改了标准输入。因此,code ... 使用连接到管道的 stdin 从 heresting 运行,并且无法从脚本的原始 stdin 读取。

而这里:

if cat <<< foo; then
    code ...
fi

...重定向的范围仅限于一个 cat 命令,并且您的 code ... 使用连接到其原始源的标准输入运行。


还需要注意的是,如果您的块是一个循环,while cat <<< foo; do code ...; done 将在每次迭代时读取一个新的 heredoc,其中正好包含 foo,而 while cat; do code ...; done <<<foo 是从单个 heredoc 读取在可能发生的尽可能多的迭代中(这意味着,在这个特定的例子中,除了第一次之外,所有的迭代都会发现输入源耗尽)。考虑 BashFAQ #1 一些例子,其中这种区别很重要。