Bash – Problem using BASH in cron (FreeBSD)

bashcronfreebsdscripting

Scenario: We have a legacy system running FreeBSD 4.7 (please, no laughing. It's being retired at the end of the year.. I just need to keep it alive and backed up until then) and I have some database dump scripts that I run daily with a cron job. I begin the script with #!/usr/local/bin/bash. The script uses the date command to put the date as part of the file name of the dump file. When I run the script manually it works as expected. However, when I put it into a cron job, it fails. I checked my error log and it's failing at the part of the script where I use backticks and the date command for the file name (I also tried $(date…) in the file name and that gave the same error. So I then tried adding /usr/local/bin/bash /path/to/script.sh in the cronjob and it still had the same error.

So my guess is that it's not switching to a bash shell when it runs. I first thought about adding echo $SHELL to my script to see, but I found that switching shells doesn't actually switch the value of the SHELL variable.

Has anyone had a similar issue with FreeBSD? Or does anyone know an alternate way I can check which shell it's using at execution? (I also tried ps >> test.txt and that didn't work in the cron either).

Best Answer

A few things occur to me while reading this.

If you are running bash echoing the value of $BASH should expand to the full path and filename of the bash executable in use.

How are you calling date in your script. Are you calling it with the full path name or as "date". The later case can result in the use of function, aliases, or whatever happens to be first in the path rather than the date program you expect.

Bash will behave differently in some cases depending on the environment. You may want to dump the environment to a file from the script and look at it running from the command-line and from cron. You may find that the PATH is different or that some other environment variable is set differently. You should be able to dump this to a file in /tmp by putting a line like "env > /tmp/environment.$$" in the script. Each time the script is run it will print out the environment to a file named environment.(pid of script)

You can set also the shell for the entire crontab to whichever shell you want by using "SHELL=/path/to/new/shell" on a line by itself.