Exit bash script on error in loop
Paul Smith
paul at mad-scientist.net
Thu Sep 12 21:47:36 UTC 2013
On Thu, 2013-09-12 at 23:16 +0200, Johnny Rosenberg wrote:
> I did some more experiments and I found that it's my pipe to a yad
> progress bar that cause the problem. Unfortunately I didn't include it
> in my example, but here's another example,
Err... yes, that makes ALL the difference.
The way the shell works with pipelines is that each section of the
pipeline is really run in a different process [*]. It pretty much HAS
to work that way since you want all the different parts of the pipeline
working at the same time, reading from and writing to pipes, and shells
are not multithreaded. Hence, different processes.
So, the exit command in the first part of the pipeline exits from that
process (shell) but doesn't exit from the parent process (main script).
There's pretty much nothing you can do about that.
Depending on exactly what you want to accomplish there may be tricks you
can play. Instead of exit, you can use kill to kill the shell script.
You can use a named pipe instead of a regular pipe, and have each
section write/read from the pipe in the background as appropriate
without using a pipeline.
Or you can switch to a more sophisticated scripting language such as
Perl or Python, that can handle this with ease.
[*] ksh has a special feature where the last element in the pipeline is
run in the current shell, which is slightly more efficient and is very
handy in some situations. But, it's not required by POSIX and not
portable, and bash doesn't implement it.
More information about the ubuntu-users
mailing list