5

I've got a script like the following:

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

The only difference between flag being true or false makes is that pipe_command_b may not be run. Is there a way to collapse this so that I don't have to repeat all of the common stuff?

Hounshell
  • 303

1 Answers1

6

Use cat instead of the command if you want to skip it:

command=cat
if [[ $flag == true ]] ; then
    command=pipe_command_b
fi
command \
    | pipe_command_a \
    | $command       \
    | pipe_command_c
choroba
  • 47,233
  • 1
    Isn't it possible that piping cat into certain commands may break things? – jesse_b Aug 03 '17 at 17:45
  • @Jesse_b: They seem to pipe the output to pipe_command_c anyway. – choroba Aug 03 '17 at 17:47
  • yea but cat also changes some results. The only one I can think of now is ls which you wouldn't want to use in a pipeline anyway but ls | cat provides a different result than just ls – jesse_b Aug 03 '17 at 17:50
  • 1
    @Jesse_b: Still the same reply. The only problem with that is when the command is the last one in the pipeline. – choroba Aug 03 '17 at 18:25
  • 3
    @Jesse_b that isn't cat "changing some results". That's ls detecting that its stdout is not a tty and producing different output (i.e. one filename per line rather than multiple filenames on multi-column line(s)). – cas Aug 04 '17 at 06:47