Search code examples
mysqlcroncron-task

mysqldump cron can't use character >


I'm trying to use a cron job task to backup my database, but when I try to add the script on the cron job it shows an error message like:

Can't set character ">"

This is the script I'm using:

mysqldump -u "username" --password='****' --no-create-info --no-tablespaces "username" > /home/"username"/public_html/_backup/db__$(date +\%Y-\%m-\%d_\%H_\%M_\%S).sql

If I run the same script via SSH console, it creates the file just fine, but I can't create the cron because of this error.

Since I'm on a shared hosting, I can't use other php functions such as exec() because they are blocked by default due to security reasons.

The support said I should escape the character because they are not allowed, but then the script fails because it's invalid. Is there a way to fix this?


Solution

  • cron just tries to start your command line without invoking a shell. The output redirection is a feature of the shell though and won't be understood by the mysqldump command.

    Now you have two options:

    1. Use a construct like "/bin/sh -c 'mysqldump ...'", which will probably cause a severe headache because of quoting issues
    2. Store the command in a shell script (don't forget to make it executable) and execute the script from cron.

    The latter method has the extra advantage that you can easily define the exact execution environment. cron usually only defines very few environment variables and this can be a pain. Within your script you can source your $HOME/.bashrc (or whatever other file), set your path variable, and so on.