How to Exit a Pipeline Early When the First Command Fails?
Asked by
CuriousCoder42
I'm working on a Bash script where I have a pipeline like `cmd1 | cmd2 | cmd3`. I want `cmd2` and `cmd3` to only run if `cmd1` is successful. Currently, I'm redirecting `cmd1`'s output to a file and using `|| exit`, but I'm looking for a cleaner way to capture the output directly into a variable instead of dealing with temporary files. Using `mapfile -t output < <(cmd1 || exit)` does not work as intended because the exit only applies to the process substitution. What's the best way to achieve this? Also, unrelatedly, I want advice on where to define my script variablesโshould I declare them at the top, when needed, or use a function to set them as global variables?
Answers
Youโve got the right idea about capturing output from `cmd1`. Instead of using the pipeline, you can do:
```bash
local output # Declare output separately to avoid issues with the local keyword.
output=$(cmd1) || exit
output=$(cmd2 <<< "$output") || exit
cmd3 <<< "$output"
```
Just keep in mind that this will run commands sequentially, which can slow things down compared to pipelines.
Reply to this answer
Add your answer
Answers are reviewed before publication.
NewbieNerd: So if the command outputs a continuous stream, does this mean that it keeps passing data to `cmd2` and `cmd3` until one of them exits?