2

This question already has an answer here:

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?

marked as duplicate by Gilles bash Feb 13 '17 at 23:21

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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
  • 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 like while 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 6: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 6:46
  • @prado Glad it worked. If helped, mark question as answered. – Rakesh.N Feb 13 '17 at 6:48
  • Bash only? Not POSIX shell? – Franklin Yu Feb 13 '17 at 9: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 9:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.