Tag Archives: locale

Bash locale problem with cron

The problem

One problem that can occur when you do bash scripting concerns the locale. If you run a script directly from the prompt or from a cron, you can have some differences.

I stumbled on that problem while writing a script to send an email containing accents (in french language) using a cron. When I was executing the script from the command line, I got the email with the accents well shaped, but once it was from the cron, it was all messed up. Problem is that they were not having the same environment. So here are two working solutions to do so.

First solution (preferred one)

Set the value of LANG inside your script, a better practice would be to put it inside a configuration file that you include. Example for the french UT8:

#!/bin/bash
export LANG=fr_FR.utf8

This solution is very practical, you get the same behavior wether you call it directly in command line or from the cron. Also the maintenance is easier, if you need to switch locale, you have your config file for this 🙂

Second solution

A more dirty and deprecated way is to write the file /etc/environment with the LANG variable too. How to do (french UTF8 example):

root@machine:~# echo "LANG=fr_FR.utf8" > /etc/environment

So as I said, this solution is deprecated and not really wise because the locale will be set for all crons ! Maybe it’s what you want, but the first solution allows you to have a different locale in different scripts.

 

P.S: “weird” behaviors can occur not only with the locale when you are using a cron, it’s possible that the PATH is different. Again you can define directly the PATH inside your script. For example, one thing you can do is an echo of the PATH in the command line, and then copy the value inside your script, this way, the cron will use the same PATH.