I went through a strange bug in a bash script which is on another machine, accessed via ssh (or other ssh like clients).
It was basically a menu, in particular showing IP address(es) of the machine it is hosted on.
The important part is this code:
#!/bin/bash
function int-ips { /sbin/ifconfig |grep -B1 "inet addr" |awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' |awk -F: '{ print $1 ": " $3 }'; }
echo $(int-ips)
(I just copy-pasted the above function from http://www.if-not-true-then-false.com/2010/linux-get-ip-address/)
It was working perfectly on F19, on Mac OS X. Then another colleague tried it from his OS X, and, surprise!, absolutely nothing was printed. The script was still being executed on the same machine, it was just accessed by ssh from another client.
It took me some time to understand it was a problem of locale: the language of the last machine was NOT English, and the function used to retrieve IP address use a "grep Link", the word "link" which happened to be translated for ifconfig with other locales, at least the one my colleague was using.
Realising the existence of an awful source of bugs, I want to know how to shield myself properly against this kind of locale-dependence issue.
For example, I know I will use the "file" command to learn filetypes about inputs, and that I will probably use "grep" or so to analyse the results.
My solution:
Add this to the beginning of my script:
export LANG=C
export LC_ALL=C
(or en_US.utf8 instead of C maybe)
My probably cleaner solution I'll do later:
- SAVE current LANG and LC_ALL
- export LANG=C ; export LC_ALL=C
- execute my locale-dependant code
- restore the user locale saved in 1)
My questions:
A) Is this fix ok? I mean, is there some experimented bash / nix coder who can warn me about some danger I don't see of using this method? (the more I get myself into nix/nux the more I'm sure of nothing :P)
B) Is there a neater / more elegant way of doing all this?
P.S. FYI, but not relevant, IMHO:
The machine hosting the script is on a VM with Centos 6.4.
The machines from which we access the VM are on Fedora 19 or Mac OS X via ssh-terminal or Windows 7 via Putty