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
elixenide
  • 44,308
  • 16
  • 74
  • 100
Lucas
  • 25
  • 4
  • 2
    `$?` is capturing the return value from sed I guess, not mysql, look here: http://stackoverflow.com/questions/1221833/bash-pipe-output-and-capture-exit-status – guido Dec 05 '15 at 23:09
  • or you can do `mysql ... < dump.sql > test.csv 2>err ; mySqlStat=$? ; sed '....' test.csv` .Good luck. – shellter Dec 05 '15 at 23:12

1 Answers1

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.

Bruce P
  • 19,995
  • 8
  • 63
  • 73
  • This fixed it. Just want to also point out (for other.. "special" people like me) PIPESTATUS may not work if you are using "sh – Lucas Dec 05 '15 at 23:55
  • Instead of inspecting `PIPESTATUS`, `pipefail` is an option that's almost always beneficial and causes no harm. – 4ae1e1 Dec 05 '15 at 23:58