有条件地在 bash 脚本中包含管道阶段

Hou*_*ell 5 bash shell-script

我有一个像下面这样的脚本:

flag=false
# Do a bunch of stuff that might set flag to true.
if [[ "$flag" == "true" ]]; then
   command \
       | pipe_command_a \
       | pipe_command_b \
       | pipe_command_c \
       | pipe_command_d \
       > "${output_path}"
else
   command \
       | pipe_command_a \
       | pipe_command_c \
       | pipe_command_d \
       > "${output_path}"
fi
Run Code Online (Sandbox Code Playgroud)

唯一的区别flagtruefalse品牌是pipe_command_b可能无法运行。有没有办法折叠它,这样我就不必重复所有常见的东西?

cho*_*oba 6

cat如果要跳过它,请使用代替命令:

command=cat
if [[ $flag == true ]] ; then
    command=pipe_command_b
fi
command \
    | pipe_command_a \
    | $command       \
    | pipe_command_c
Run Code Online (Sandbox Code Playgroud)

  • @Jesse_b 不是“cat”“改变一些结果”。那是 `ls` 检测到它的 stdout 不是一个 tty 并产生不同的输出(即每行一个文件名,而不是多列行上的多个文件名)。 (3认同)