0

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:

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/opt/jdk/jdk1.6.0_35/bin

The wrong one that sometimes occurs is:

SHELL=/bin/sh
PATH=/usr/bin:/bin

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
  • 2
    Have you started your script with #!/bin/bash?
    – davids
    Nov 20, 2012 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, 2012 at 11:44

3 Answers 3

2

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

#!/bin/bash

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.

1
  • 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... Nov 20, 2012 at 13:48
0

Put this in the very start of your script:

#!/bin/bash
if [ "$(readlink -f /proc/$$/exe)" != "/bin/bash" ] ; then
    echo restarting script with bash... > &2
    exec /bin/bash $0 "$@"
fi
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)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .