Posts Tagged bash
Using the ‘date’ command in your crontab
Crontab, as most people know, enables users to schedule commands or shell scripts to run periodically at certain times or dates.
The other day, this very useful Linux tool gave me a hard time! π
Indeed, one of my commands wasn’t working in cron but was working perfectly fine when written in a shell console.
The faulty command looked like this:
0 5 * * 3 /data/script.sh > /data/script_`date +%y%m%d`.log 2>&1
If I run this command in a shell console, everything works fine and I get a log file containing today’s date in its filename. However, if I set this command line in my crontab, it doesn’t work and no log file is even created!
Reading the documentation of cron, I discovered the following statement:
Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.
Well, this is good to know, isn’t it? π
We need to escape the percent-signs on our command line.
So in order to get our ‘faulty’ command to run in cron, it needs to look like the following:
0 5 * * 3 /data/script.sh > /data/script_`date +\%y\%m\%d`.log 2>&1
Locale settings for your cron job
Do you get special characters problem when executing your bash script from a cron job?
And does the same script work fine when it is directly executed from the command line?
If yes, continue reading this article! π
The reason of this characters problem is probably because of your locale settings.
Indeed, If you try to run the command locale
from the command line and from a cron job, you may get different results such as:
From the command line | From a cron job |
LANG=en_US.UTF-8 LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER="en_US.UTF-8" LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT="en_US.UTF-8" LC_IDENTIFICATION="en_US.UTF-8" LC_ALL= |
LANG= LC_CTYPE="POSIX" LC_NUMERIC="POSIX" LC_TIME="POSIX" LC_COLLATE="POSIX" LC_MONETARY="POSIX" LC_MESSAGES="POSIX" LC_PAPER="POSIX" LC_NAME="POSIX" LC_ADDRESS="POSIX" LC_TELEPHONE="POSIX" LC_MEASUREMENT="POSIX" LC_IDENTIFICATION="POSIX" LC_ALL= |
As you can see, the cron job is not using UTF-8. That must be the problem! π
So the question now is how to change the locale settings for the cron job?
Some people say that you need to add the following environment variables to the crontab entry:
SHELL=/bin/bash LANG=en_US.UTF-8 LANGUAGE=en LC_CTYPE=en_US.UTF-8
But this actually didn’t work for me. π
What you can do instead is create (if not already present) the file /etc/environment
and add the following line:
LANG=en_US.UTF-8
The cron process will read this file when it starts, so you need to restart it in order to apply the change:
service cron restart
Hope this will fix your characters problem. π