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
Prosty skaner portów TCP w bash
Viewed 3883 times since Thu, May 24, 2018
KONTO SFTP Z CHROOTEM Z UŻYCIEM OPENSSH-SERVER NA CENTOS/RHEL6
Viewed 2440 times since Fri, Nov 30, 2018
LVM: Reduce an existing Logical Volume / Filesystem
Viewed 4153 times since Sat, Jun 2, 2018
HowTo: The Ultimate Logrotate Command Tutorial with 10 Examples
Viewed 6552 times since Fri, Nov 30, 2018
What Is /dev/shm And Its Practical Usage
Viewed 8919 times since Tue, Mar 12, 2019
20 IPtables Examples For New SysAdmins
Viewed 2784 times since Fri, May 15, 2020
RHEL: Route network packets to go out via the same interface they came in
Viewed 3932 times since Sat, Jun 2, 2018
Linux - How to get network speed and statistic of ethernet adapter in Linux
Viewed 2780 times since Fri, Jun 8, 2018
RHEL: Retrieve and generate a unique SCSI identifier
Viewed 3956 times since Sat, Jun 2, 2018
LVM: Create a new Volume Group
Viewed 2629 times since Sat, Jun 2, 2018