Cron error with using backquotes

2020-03-12 07:24发布

问题:

The following works fine from command line

/usr/bin/mysqldump -uUser -pPass Db_name > /var/www/db_backup/db.`date +%Y%m%d%H%M`.sql 

but when I try to do that in cron, I get the error:

bad ` sign 
errors in crontab file, can't install

I saw someone else on the net solve the same problem by escaping the percent signs, but that didn't help and I tried it with just date inside backquotes with no format specifiers and still got the errors.

I've also seen date's argument enclosed in single or double quotes, but that doesn't help either.

Granted I could just throw it into a script and execute that I suppose - but what fun is that?

Any ideas? I'm using RHEL 5.

回答1:

Try it with $() instead of backticks. And you probably do need to escape the percent signs since cron converts them to newlines otherwise.

* 0 * * * /usr/bin/mysqldump -uUser -pPass Db_name > /var/www/db_backup/db.$(date +\%Y\%m\%d\%H\%M).sql

Also, you should store the password in an option file with secure permissions (eg. 600 or 640) instead of passing it on the command line.



回答2:

Put your one line script (as shown) into a proper script file and invoke that from cron:

$ cat /usr/local/bin/db-backup
#!/bin/sh
/usr/bin/mysqldump -uUser -pPass Db_name > \
   /var/www/db_backup/db.`date +%Y%m%d%H%M`.sql 
$ # use RHEL commands to add db-backup to your crontab


标签: linux shell cron