I'm having a strange behaviour with a shell script on Ubuntu 12.04.1 LTS.

My script is scheduled to be launched every hour (in crontab). It uses /bin/bash, but sometimes it switches to /bin/sh without any reason.

Here are some portions of the env command that I'm logging from within the script.

The correct one is:


The wrong one that sometimes occurs is:


The problem is that I'm losing the PATH variable and I gets an error when I try to run a command.

Any hint? Thanks!

  • 2
    Have you started your script with #!/bin/bash? – davids Nov 20 '12 at 10:03
  • The first $PATH is the one for your user, the second $PATH is the one for cron. Make a tiny cron wrapper which launches /bin/bash and sets up your expected $PATH. – cdleonard Nov 20 '12 at 11:44

It's hard to tell why it sometimes works and sometimes doesn't. So here's some ideas that might or might not help.

Check your script starts with


and make sure the script is run with the correct user: This will make bash load the correct environment for that user.

If you want go sure, you can also explicitly run bash in your crontab, then pass the script to run with the -c argument.

If that doesn't help and you need a quick fix, you might choose to run the commands in your script using their full path, so you don't need the correct PATH at all.

Side note: This question would better fit into Server Fault or Unix and Linux.

  • Thanks, the script starts with the /bin/bash declaration. However, I've already found some workarounds that fix the problem like the ones you're suggesting. I can't explain why this happens anyway... – Angelo Cavallini Nov 20 '12 at 13:48

Put this in the very start of your script:

if [ "$(readlink -f /proc/$$/exe)" != "/bin/bash" ] ; then
    echo restarting script with bash... > &2
    exec /bin/bash $0 "$@"

The SHELL variable is the login shell, not necessarily the shell you are currently running under.

The most likely reason for the differences is that sometimes you are running from an interactive shell, and sometimes not (cron), in each case the start-up files that are run are different.

When you run under cron it is not a login shell, so your .profile is not being run - the most likely reason why your PATH is different.

At the start of your script put:

source ~/.profile

(or use . instead of source)

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.