blob

Mein Haus, meine Straße, mein Blob

Sep 16, 2012

Creating language agnostic shell scripts

Usually, when writing a shell script that relies on parsing the output of some other program — using grep, awk or whatever the text manipulation tool of your choise is — I check the output of the command on my machine and write my regex accordingly. What I — and lots of other people, it seems, when you look at the scripts you find online for any given problem — tend to forget: Even though I consider it almost mandatory to have my servers' shells set to English, not everybody uses English as the default language for their system and thus, your carefully tested regex either fails to parse the output or, even worse, parses wrong values, causing your script to misbehave in unforeseeable ways.

Fortunately, forcing your script to run with a locale of your choice is simple. Given you want your script to use the 'C' locale, which is plain ASCII english and available on every machine, simply add the following as your first command to your script. This will cause the script to print all messages, times, and numbers using the given locale without changing any systemwide settings.

LC_ALL=C

You could also use LANG, but that setting might be overridden if the user has LC_ALL set.

Resources

This Ubuntu help page has a list of all language related environment variables.

posted at 15:32  ·   ·  linux  shell