Search code examples
shellubuntucron

register crontab using text file on www-data account


Trying to register crontab using text file, but cronjob Is in www-data account.

What I tried is

sudo -u www-data crontab.bak | crontab -

However it doesn’t work. I wonder if this is possible to register crontab using text file on www-data account.


Solution

  • sudo -u www-data crontab.bak | crontab -
    

    I'm assuming that crontab.bak includes the crontab entries that you want to add to the crontab for the www-data account. (You didn't clearly say that in your question.)

    This command:

    sudo -u www-data crontab.bak
    

    attempts to run the command crontab.bak under the www-data account. Since crontab.bak is not a command, that doesn't work. It should give you an error message like

    sudo: crontab.bak: command not found
    

    -- which you should have included in your question.

    Furthermore, the sudo applies only to the first command in your pipeline. In general, if you do

    sudo -u www-data command1 | command2
    

    it will run command1 under the www-data account, but it will run command2 under your account. It's the crontab command that you want to run as www-data.

    If the www-data account has permission to read the crontab.bak file, you can do this:

    sudo -u www-data crontab crontab.bak
    

    If not, you'll have to read the file from your own account and feed the output to the crontab command running under the www-data account:

    cat crontab.bak | sudo -u www-data crontab -
    

    Or, since this is a Useless Use of cat:

    sudo -u www-data crontab - < crontab.bak
    

    To be clear, in this final version the crontab command runs as www-data and reads from its standard input, and the redirection < crontab.bak is handled by the shell running under your account.