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
stunnel bacula
Viewed 847 times since Fri, Sep 28, 2018
YUM How to use yum command on CentOS/RHEL
Viewed 2877 times since Thu, Oct 25, 2018
RHEL: Crash kernel dumps configuration and analysis on RHEL 5
Viewed 1628 times since Sat, Jun 2, 2018
How to run command or code in parallel in bash shell under Linux or Unix
Viewed 1150 times since Tue, Aug 6, 2019
RHCS6: Debug and test multicast traffic between two hosts
Viewed 1088 times since Sun, Jun 3, 2018
LVM: Reduce an existing Volume Group by removing one of its disks
Viewed 922 times since Sat, Jun 2, 2018
RHEL7: Create and configure LUKS-encrypted partitions and logical volumes to prompt for password and mount a decrypted file system at boot.
Viewed 2715 times since Mon, Aug 6, 2018
Tunnel SSH Connections Over SSL Using ‘Stunnel’ On Debian 7 / Ubuntu 13.10
Viewed 1025 times since Fri, Sep 28, 2018
Understanding System auditing with auditd
Viewed 2640 times since Fri, Apr 5, 2019
RHEL: Remove existing SAN LUNs
Viewed 1257 times since Sat, Jun 2, 2018