Bash – How to use Locale-Specific Translation in Bash

bashlocale

Going through the bash manual I found the Locale-specific translation section Bash Reference Manual → 3.1.2.5 Locale-Specific Translation:

3.1.2.5 Locale-Specific Translation

A double-quoted string preceded by a dollar sign (‘$’) will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted.

Some systems use the message catalog selected by the LC_MESSAGES shell variable. Others create the name of the message catalog from the value of the TEXTDOMAIN shell variable, possibly adding a suffix of ‘.mo’. If you use the TEXTDOMAIN variable, you may need to set the TEXTDOMAINDIR variable to the location of the message catalog files. Still others use both variables in this fashion: TEXTDOMAINDIR/LC_MESSAGES/LC_MESSAGES/TEXTDOMAIN.mo.

So I decided to test it.

My machine uses the English US locale:

$ echo $LANG
en_US.UTF-8

And writing an English word worked well:

$ echo $"Hello"
Hello

I checked which locales are available here and found out many:

$ locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
...
en_ZM.utf8
en_ZW.utf8
es_ES.utf8
POSIX

So I decided to test this functionallity with Spanish. However, changing the locale did not make the translation to be triggered:

$ LANG=es_ES.UTF8 echo $"Hello"
Hello              # Still in English. Should be "Hola", in Spanish

Why is that? What am I missing here? I suspect there is a set of words that are translated somewhere, but I cannot find out where.

This is my Bash version:

$ bash --version
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

Best Answer

You are missing making the actual translation. (The computer does not know English or Spanish, all it knows is to look up the string in a catalog.) See Localization in the Advanced Bash Scripting Guide. See the FAQ for a worked-out example. There is security warning for the construct $"..."; in practice this means that you must protect the translations file as well as the script itself.