Bash – change locale in script

bashlocale

I made an script that do some math, using bc and printf.

It worked well under cygwin which locale is en_US.UTF-8, but when I run it under linux, which locale is en_ES.UTF-8, it fails because it uses , as decimal separator. For example next expression fails:

avg=$(printf %.2f $(echo "scale=4; $val1/$val2" | bc -l )) 

I found a solution. Precede the script by LC_ALL=C.UTF8:

LC_ALL=C.UTF8 ./script.sh [OPTIONS] 

However, I think it would be better not to do that.
So, my question: Is there a way to change locale only inside the script, to avoid such kind of problems, regardless of locale set in user profile?

Best Answer

Inside the script, simply export LC_ALL=C.UTF-8ยน at the beginning (just after the shebang line, if any).

Then, all commands executed by the script will inherit LC_ALL.

If you need part of your script to be immune to locale changes, but part to respect the locale (for instance, if you are to calculate and then print some values), you might need to unset LC_ALL after the calculation and before the printing. Alternatively, you might choose to prefix just some commands in your script with a per-command setting.


  1. Some platforms spell the UTF-8 version of C locale differently (different case and/or lack of hyphen in UTF-8). A more platform-independent version is:

     export LC_ALL=$(locale -a|grep -ix 'c.utf-\?8' || echo C)
    
Related Question