Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining pipe with exit status in bash shell script

I have this bash shell-script command that causes date to run if make succeeds (terminates with zero exit status) and vice versa:

make && date

but now I want to process its output e.g.

make | sed s/a/A/

If I do

make | sed s/a/A/ && date

date runs even when make fails.

If I instead do

make && date | sed s/a/A/

the sed processes date's output instead of make's.

Would you know of any solution? Thanks!


P.S. I've tried these:

(make | sed s/a/A/) && date

date still runs when make fails.

(make && (date > /dev/null)) | sed s/a/A/

date doesn't run when make succeeds.

like image 843
Gnubie Avatar asked Sep 09 '11 11:09

Gnubie


1 Answers

If you do have a shell with process substitution (bash does, posix shell is not), than

make > >(sed s/a/A/) && date

should do the trick, except bash it does not wait for the sed (it seems zsh does, but I only tried it, not checked the doc), so the output of date can get before the last line of sed output. In plain posix shell, you can use a bit more complicated construct

((make && date >&3) | sed s/a/A/) 3>&1

The date can again run before sed has processed everything, so it's output can again come before the last line of sed output.

If you want the date to only run after the sed has processed everything, your only chance is storing the make status somewhere. Something like:

(make && touch make-succeeded) | sed s/a/A/
rm make-succeeded 2>/dev/null && date

abusing the fact, that if the file does not exist, rm (without -f) will exit with nonzero status and silencing it's error message with redirection. As Fredrik has mentioned though, bash does in fact have a place where it does stash the exits status, so in bash you can:

make | sed s/a/A/
[ 0 -eq $PIPESTATUS[0] ] && date
like image 83
Jan Hudec Avatar answered Oct 21 '22 10:10

Jan Hudec