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?

0

1 Answer 1

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

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