You are not logged in.

#1 2010-10-12 19:58:41

hut
Member
From: Hanover, Germany
Registered: 2010-03-12
Posts: 569
Website

Bash, pipes and exit values...

You can run something like this in bash:

command1 && foo || bar

1. foo will run only when command1 succeeds (exit code 0)
2. bar will run only when command1 or foo succeeds.

Random example:

test -f ~/.config && echo "config already exists!" || touch ~/.config

My question is: Is there a straightforward way to pipe command1 into e.g. tail and still using the exit code of command1? This way doesn't work since the exit code of tail is used which is always 0.

command1 | tail && foo || bar

My specific situation looks like this: I need a different exit code of the whole script (or possibly no exit at all), depending on the exit code of command1.

command1 | sed 's/a/b/;' && exit $X || exit $Y

"hut_" or "h00th00t" in irc.freenode.net #archlinux
Ranger Mailing List: https://lists.nongnu.org/mailman/listinfo/ranger-users

Offline

#2 2010-10-12 20:14:46

portix
Member
Registered: 2009-01-13
Posts: 757

Re: Bash, pipes and exit values...

The exitcodes of all commands in a pipe are in the PIPESTATUS-array.

Offline

#3 2010-10-12 21:04:15

hut
Member
From: Hanover, Germany
Registered: 2010-03-12
Posts: 569
Website

Re: Bash, pipes and exit values...

Well thank you very much. I'll do something like this then:

command1 | tail
test ${PIPESTATUS[0]} == 0 && foo || bar

"hut_" or "h00th00t" in irc.freenode.net #archlinux
Ranger Mailing List: https://lists.nongnu.org/mailman/listinfo/ranger-users

Offline

#4 2010-10-13 02:03:24

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,110
Website

Re: Bash, pipes and exit values...

Wow, didn't know about PIPESTATUS. Neat-o.

Alternatively, you can enable the shell option pipefail. From bash(1):

The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled.  If pipefail is enabled, the
pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit success‐
fully.   If  the  reserved  word  !   precedes  a  pipeline, the exit status of that pipeline is the logical negation of the exit status as
described above.  The shell waits for all commands in the pipeline to terminate before returning a value.

Offline

#5 2010-10-13 21:29:31

thestinger
Trusted User (TU)
From: Toronto, Canada
Registered: 2010-01-23
Posts: 478

Re: Bash, pipes and exit values...

also check out mispipe in the moreutils package

http://linux.die.net/man/1/mispipe

Offline

Board footer

Powered by FluxBB