The real problem is that with a pipe, the default return status is the exit code of the last command (bzip2
). To quote man bash
:
The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit success‐ fully.
If you want to report failure if any command of the pipe failed, you have to set the pipefail
option. Assuming bash
, here is an example (I don't have mysql server running on localhost):
sylvain@daal:~$ set -o pipefail
sylvain@daal:~$ if mysqldump -u root -p db | bzip2 -c > latest-dump.mssql.bz2; then echo ok; else echo non ok; fi
Enter password:
mysqldump: Got error: 2002: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) when trying to connect
non ok
For your particular case, you will write something like:
set -o pipefail
if ${l_mysqldump:-mysqldump} -u$l_db_user -p$l_db_pass -h $l_db_host $l_db_name | bzip2 -c > latest-dump.mssql.bz2
then
...
fi
BTW: "mysqldump command gives this error [..] Even though it throws up this error, it still generates a 0 byte .mssql file."
To be more precise, since you use shell redirection, it is the host shell that create the file. Before it even tried to run the command.