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:
1
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.
1
2
echo $?
0

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:
1
2
3
4
5
6
7
8
mysqldump -u $USERNAME -p $PASS $DBNAME | bzip2 -9c -c > Dump.sql.gz
 
if [ ${PIPESTATUS[0]} -ne "0" ]
then
    echo "the MySQL Database backup failed with Error: ${PIPESTATUS[0]}";
else
    echo "The MySQL Database backup was successfull!";
fi
0 (0)
Article Rating (No Votes)
Rate this article
Attachments
There are no attachments for this article.
Comments
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
RHCS6: Reduce a Global Filesystem 2 (GFS2)
Viewed 1302 times since Sun, Jun 3, 2018
RHEL: Extending a multipath LUN
Viewed 2276 times since Sun, May 27, 2018
Using Official Redhat DVD as repository
Viewed 9211 times since Mon, Oct 29, 2018
RHEL : How to deal with “CLOSE_WAIT” and “TIME_WAIT” connection
Viewed 13986 times since Thu, Feb 14, 2019
Use inotify-tools on CentOS 7 or RHEL 7 to watch files and directories for events
Viewed 11176 times since Fri, Jul 27, 2018
How to Clear RAM Memory Cache, Buffer and Swap Space on Linux
Viewed 744 times since Mon, Nov 23, 2020
how to list all hard disks in linux from command line
Viewed 1110 times since Mon, Jan 28, 2019
Moving SSL Certificate from IIS to Apache
Viewed 803 times since Mon, Feb 18, 2019
VMWare tools free
Viewed 6463 times since Mon, Jul 16, 2018
Linux - How to shutdown or reboot
Viewed 887 times since Fri, Jun 8, 2018