How to Exit a Pipeline Early When the First Command Fails?

0
5
Asked By CuriousCoder42 On

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?

1 Answer

Answered By BashGuru99 On

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.

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?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.