[NTLUG:Discuss] Catching exit code in a pipe?

Patrick R. Michaud pmichaud at pobox.com
Thu Apr 22 23:28:49 CDT 2010


On Thu, Apr 22, 2010 at 10:11:55PM -0500, David Stanaway wrote:
> I have a backup script that includes:
> 
> su -c "pg_dumpall | gzip -9 > backup/db.out.gz" -l postgres
> 
> $? gets the most recent pipelined command exit, and catches the gzip
> exit code which is always 0.
> 
> I don't want to create an intermediate file uncompressed.
> 
> Does anyone have an idea how I can do this in bash without getting too
> creative with subshells and signal handlers?

Perhaps...?

  su -c "set -o pipefail; pg_dumpall | gzip -9 > backup/db.out.gz" -l postgres

The "pipefail" option in bash(1) causes the pipeline to 
return the exit code of the last failing command in the 
pipeline.  So in the above, since the gzip always exits with zero,
the returned exit code will come from the pg_dumpall command.

Pm



More information about the Discuss mailing list