bash give me a one liner where I run a command, and its return code is 0, pipe the…
- User
bash give me a one liner where I run a command, and its return code is 0, pipe the output to another command
- Assistant
To run a command and only pipe its output to another command if its return code is 0, you can use a combination of
&&and a pipe (|). Here is a one-liner example:bashcommand1 && command1 | command2Replace
command1with the command you want to execute initially, andcommand2with the command you want to pipe the output into. This one-liner ensures thatcommand1is executed, and if it succeeds (return code is 0), its output is then piped intocommand2. - User
without executing command1 twice
- Assistant
Certainly! To achieve this without running
command1twice, you can utilize process substitution in combination withtee. Here is the one-liner:bashcommand1 | tee >(command2) > /dev/nullIn this approach,
command1is executed once. The output is simultaneously piped intocommand2usingteeand process substitution. The> /dev/nullpart discards the original output, ensuring only the pipe intocommand2matters. Ifcommand2should not see the output unlesscommand1succeeds, you can structure the one-liner conditionally:bashcommand1 > >(command2)Here,
command2will receive the stdout ofcommand1. If you require thatcommand2should process the stdout only ifcommand1completes with a status of 0, ensurecommand1would naturally terminate with a successful exit status as required in conditional scenarios.