The True Story of Unix Shell 'IF'
I came across an issue with one of my server scripts while I was giving it a refresh this morning. The script is a backup script that lives on every single box of my cluster, whose purpose is to back up each box according to its individual role in the cluster.
So I wished to (pseudo)code the following:
thisbox = gethostname
if thisbox is a front server then do backup front files
if thisbox is a back server then do backup databases
Which I all too quickly translated into a shell script as follows:
HOST=`hostname -s`
if [$HOST=='ns6511']
then
# do somthing
fi
And guess what? You’re right, it doesn’t work. The shell complains as follows (HOST contains ‘ns6511′ on this box):
/home/mobiluck/backup/mlo.backup.sh: line 28: [ns6511: command not found
It simply shocked me in the very first seconds I read this error message, before I quickly had a “Eureka” moment.
What you might consider pure shell syntax — the square brackets — actually isn’t! So what is it?
[ is a Linux command — I mean an executable file, which you can see by running this on your own box:
# l /usr/bin/[
-rwxr-xr-x 1 root root 29K aoû 28 11:59 /usr/bin/[
Alright, [ is a command. So what? Why the hell does my script fail?
It fails because I forgot to put spaces between the command and its arguments! Hence the command it thought I was trying to run was [ns6511.
In fact, $HOST, ==, ns6511, and ] are the arguments of the [ command.
So insert all the missing spaces between the command and its arguments and everything will work as expected.
Finally, the correct syntax is obviously as follows:
<pre>
<code>
HOST=`hostname -s`
if [ $HOST == ‘ns6511′ ]
then
- do somthing
fi
</code>
</pre>
I hope this reminder pleased you, and this learning session proves something important: how Unix — which, at first sight, could be considered a deprecated technology from the ‘70s — really is not. The answer is probably: simplicity.
And simplicity here means power and evolution.