2

I have a cron job I need to run as root and that needs bash rather than the default sh shell.

The root crontab has other jobs in it that run fine as they are and I'd rather not risk breaking those by specifying SHELL=/bin/bash at the top of the crontab file.

How can I specify my cron job is to be run using bash without changing the shell used for other existing jobs?

I'm kind of thinking that a line like 0 * * * * SHELL=/bin/bash myjob might do the trick, but I can't find that mentioned anywhere in the CentOS documentation for cron.

I also thought that maybe setting the SHELL variable immediately before my job (which would be the last one in the file) might work, but couldn't find an documentation of the effect of placement of environment variables and whether they were assigned in document order or were just considered global regardless of their position (or perhaps generated an error if not before all jobs).

Is it possible for me to specify the shell on a job-by-job basis?

6

The most straight-forward way to specify the shell is simply to invoke that shell's executable file. For example, if you want to execute a command called myjob using bash, you could use something like the following command-line:

/bin/bash -c 'myjob'

The corresponding crontab entry might look like this:

0 * * * * /bin/bash -c 'myjob'

Alternatively, if myjob is a script, you might use something like the following command-line instead:

/bin/bash '/path/to/myjob'

And the corresponding crontab entry for that would be something like this:

0 * * * * /bin/bash '/path/to/myjob'
1

If myjob is a shell script, make sure that it is executable and that it's #!-line specifies the correct interpreter for the script file (e.g. #!/bin/bash). That's all.

If it's a series of commands, I'd recommend putting those in a bash script, with a proper #!-line, as above.

This way, you don't really have to worry too much about the particularities of getting the crontab entry correct (apart from at what times to run the script). It also removes the need to update the cronjob when you reimplement the script in Python or Perl or some other shell variant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.