Alvin Bakker Alvin Bakker - 3 months ago 18
Bash Question

Shell script for making database backups works only from prompt

I have a shell script that works fine from the command prompt, but from my cron job it throws

unexpected operator


BACKUP=/var/www/backups/mysql
NOW=$(date +"%Y%m%d-%H%M")
MUSER="root"
MPASS="secr3T"
MHOST="localhost"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"

find $BACKUP/* -mtime +15 -exec rm {} \;

DBS="$($MYSQL -h $MHOST -u $MUSER -p$MPASS -Bse 'show databases')"
for db in $DBS
do

if [ "$db" == "myDBase" ]; then
if [ "$db" != "performance_schema" ]; then
FILE=$BACKUP/mysql_backup_$db.$NOW.tar.gz
$MYSQLDUMP -h $MHOST -u $MUSER -p$MPASS $db | $GZIP -9 > $FILE
echo $db
fi
fi
done


I am accessing the script using crontab
20 0 * * * var/www/backups/backup.site.sh


The errors I get are:

/var/www/backups/backup.mysql.sh: 20: [: information_schema: unexpected operator
/var/www/backups/backup.mysql.sh: 20: [: mysql: unexpected operator
/var/www/backups/backup.mysql.sh: 20: [: olb: unexpected operator
/var/www/backups/backup.mysql.sh: 20: [: performance_schema: unexpected operator


I am running the latest version of mySQL on Ubuntu 14.04. Doe anyone have an idea why?

Answer

Without specifying your shell, you will get /bin/sh by default (tested on Ubuntu 14.04). The [ built-in for sh does not support the == operator, so sh doesn't know how to compare $db and myDBase on line 20.

You should always start your scripts with a "#!" line to specify a shell. To get bash, the first line would be #!/bin/bash.