1

I am working on a bash script to dump a database to a file to be uploaded via FTP. It will be launched by a cron job and the sql server isn't localhost.

I have the script working but am running into a road block with error checking. If the script cant connect to the sql server (in the unlikely event that it goes down) I want it to stop and output whatever the problem was to an error log. The outputting to error log works fine, but the script still runs and creates a blank file. I am trying to use the $? to check if the mysql connection failed and even when I am using a testing server that is off, a 0 is returned instead of a 1. I'm wearing a hole in the wall that I am bashing my head against, what am I doing wrong?

If this has been asked before, please point me in the right direction but I couldn't find any answers when I searched.

contents of the bash script:

{  
mysql -h $HOST -u $USERNAME -p$PASSWORD < dump.sql | sed "s/\t/\",\"/g;s/^/\"/;s/$/\"/" > test.csv  
} 2>error.log  
if [ $? -ne 0 ]; then { echo "SQL Server connection failed. Aborting" ; exit 1; } fi
2
  • 2
    $? is capturing the return value from sed I guess, not mysql, look here: stackoverflow.com/questions/1221833/… Commented Dec 5, 2015 at 23:09
  • or you can do mysql ... < dump.sql > test.csv 2>err ; mySqlStat=$? ; sed '....' test.csv .Good luck. Commented Dec 5, 2015 at 23:12

1 Answer 1

1

$? in this case is returning the result of your sed command, not the mysql command. Since the sed command is always succeeding (you're passing valid input to it and a valid set of substitutions) you're always going to get 0 in $?.

When using one or more piped commands in a bash script then you want to use the built-in PIPESTATUS variable which will let you examine the return value of each command in a series of piped commands, no matter how many you pipe together.

Sign up to request clarification or add additional context in comments.

2 Comments

This fixed it. Just want to also point out (for other.. "special" people like me) PIPESTATUS may not work if you are using "sh <script>" which I was. You need to chmod +x the script and run "./ <script>". This was why my previous forays into PIPESTATUS were not working as what info I found assumed you had chmod'ed already.
Instead of inspecting PIPESTATUS, pipefail is an option that's almost always beneficial and causes no harm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.