Linux – How to check the exit status of several piped commands

As piping in bash commands is common and very usefull, controling the exit status of each piped commands in bash scripting can be vital, especially for backups.

I was checking by a customer the backups of a critical MySQL instance and was surprised even stunned that the return status of all of them was always  successfull when tested but physically on disk, the dumps were all empty.
No valid backups since a long time meaning no possible recovery.
Oups! How can it be?
I immediately opened the backup script with “vi” and had a look to the used statement which was the following:
mysqldump -u $USERNAME -p $PASS $DBNAME | bzip2 -9c -c > Dump.sql.gz
Now, what if the backup failed and the bzip2 command succeeded?
In fact, the exit status will be the one of the last command.
echo $?

And this will be always successfull.

So, the  solution to check the exit status of a particular command in piped commands is to use an inbuilt linux variable called  PIPESTATUS.
PIPESTATUS is an array variable which contain the exit status of every piped commands.
In our case,
echo ${PIPESTATUS[0]} will refer to the backup  and will be greater than 0 if it fails
echo ${PIPESTATUS[1]} will refer to the compression
echo ${PIPESTATUS[*]} or echo ${PIPESTATUS[@]} will give you the status of both.
So, one solution in our example could be:
mysqldump -u $USERNAME -p $PASS $DBNAME | bzip2 -9c -c > Dump.sql.gz
if [ ${PIPESTATUS[0]} -ne "0" ]
    echo "the MySQL Database backup failed with Error: ${PIPESTATUS[0]}";
    echo "The MySQL Database backup was successfull!";
0 (0)
Article Rating (No Votes)
Rate this article
There are no attachments for this article.
There are no comments for this article. Be the first to post a comment.
Full Name
Email Address
Security Code Security Code
Related Articles RSS Feed
RHEL: Getting/Setting hardware clock’s time
Viewed 1102 times since Sat, Jun 2, 2018
Tropienie pożeracza dysku
Viewed 983 times since Thu, May 24, 2018
SSH ProxyCommand example: Going through one host to reach another server
Viewed 2592 times since Tue, Aug 6, 2019
WatchDog script for checking server running
Viewed 2249 times since Tue, Jul 31, 2018
Method 2 – Use shell scripts How to install yum cron on a CentOS/RHEL 6.x/7.x
Viewed 660 times since Tue, Dec 4, 2018
How to schedule crontab in Unix Operating Systems
Viewed 651 times since Fri, Jun 8, 2018
Modifying the inode count for an ext2/ext3/ext4 file system
Viewed 155 times since Fri, Sep 18, 2020
HP-UX - Stunnel Configuration
Viewed 522 times since Fri, Sep 28, 2018
Extending Linux LVM partitions script
Viewed 600 times since Wed, Feb 6, 2019
python learning
Viewed 537 times since Wed, Dec 18, 2019