“确保不要在同一个管道中读写同一个文件”

Tim*_*Tim 0 bash shellcheck

shellcheck 报告:

echo -e "blah/blah\n$(cat "$tmpdir"/"$filename".jpdf)" > "$tmpdir"/"$filename".jpdf
                          ^-- SC2094: Make sure not to read and write the same file in the same pipeline.
                                                         ^-- SC2094: Make sure not to read and write the same file in the same pipeline.
Run Code Online (Sandbox Code Playgroud)

blah/blah该命令的目的是在文件的开头插入一行"$tmpdir"/"$filename".jpdf

“确保不在同一管道中读取和写入同一文件”是什么意思?

我该怎么办呢?

谢谢。

Wei*_*hou 8

正如其他答案所指出的,它警告您读取和写入同一文件将擦除该文件。原因是>导致文件在输入完成之前被截断。

你有两个选择,

  1. sponge从包装中取出使用moreutilssponge确保输入在通过管道传送到下一个命令之前被完全消耗。

    代替

    command "$file" > "$file"
    
    Run Code Online (Sandbox Code Playgroud)

    command "$file" | sponge "$file"
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将输出重定向到另一个文件,然后重命名。

    像这样

    command "$file" > "$file2" && mv "$file2" "$file"
    
    Run Code Online (Sandbox Code Playgroud)

关于您的具体问题:在文件中添加“blah/blah”,sed如果它支持该-i选项,则可以使用。举GNU sed个例子:

sed '1i\
blah/blah' -i "$file"
Run Code Online (Sandbox Code Playgroud)