2

I am running this while loop in a script to take mysqldump and compress it, but I want to exit the script if the table doesn't exist. Below is what I have tried.

while read TABLES; do
    sudo mysqldump $DB $TABLES | gzip -f > $DB.$TABLES.sql.gz
    if [ $? != 0 ]; then
        echo "mysqldump Query executed with error !!"
        exit 1
    fi
done < file

But this will give the exit status of gzip -f, but not of mysqldump. I know I can get the exit status of mysqldump if I am not using gzip there, but is there any way in this method to get the exit ststus for mysqldump?

prado
  • 930
  • 1
  • 11
  • 33

1 Answers1

6

you can make use of PIPESTATUS variable to get the exit status of each element of the pipeline.

if [ ${PIPESTATUS[0]} -ne 0 ];then
        echo "mysqldump Query executed with error !!"
        exit 1
    fi
Rakesh.N
  • 802
  • Unfortunately I am not getting the expected result. `++ sudo mysqldump mysql use mysqldump: Couldn't find table: "use"
    • '[' 0 -ne 0 ']'
    • read TABLES. I used likewhile read TABLES; do sudo mysqldump $DB $TABLES | gzip -f > $DB.$TABLES.sql.gz; if [ ${PIPESTATUS[0]} -ne 0 ];then echo "mysqldump Query executed with error !!";exit 1;fi;done < file`. Am I doing something wrong?
    – prado Feb 13 '17 at 06:37
  • I got it right now. I had backticks in the script which was causing the issue. Removing it will work. Thanks @rakesh – prado Feb 13 '17 at 06:46
  • @prado Glad it worked. If helped, mark question as answered. – Rakesh.N Feb 13 '17 at 06:48
  • Bash only? Not POSIX shell? – Franklin Yu Feb 13 '17 at 09:17
  • @ Franklin Yu executiing this script in posix mode, it's giving a proper output. P.S : not much hands on experience/knowledge in posix. – Rakesh.N Feb 13 '17 at 09:40
  • If you ran out of disk gzip will give an error so you also need to check for ${PIPESTATUS[1]} -ne 0. The result is an array ${PIPESTATUS[@]} = 0 0. – hschou Feb 13 '17 at 16:11