The True Story of Unix Shell 'IF'

Jan. 28th, 2009 13:16 by Stéphane de LucaPermalink | TrackBack: https://stephanedeluca.com/trackback/858 — exists for 15 years & 2 months ago  Content not available in English.

I came across an issue with one of my server script while I was giving it a refresh this morning. The script is a backup script that lays on every single box of my cluster which purpose is to make the backup of each box in regards of each individual box role in the cluster.

So I which 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 too much quickly translated in shell script as follows:


HOST=`hostname -s`

if [$HOST=='ns6511']
then
# do somthing
fi


And guess what? you're right, it doesn't work. Shell complains as follows (HOST contains 'ns651' 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 report, but quickly felt as Newton did with his "Eureka".

What you might consider as a pure sheel syntax -- the square brackets -- is not actually! So what's this?

[ is a linux command -- I mean an executable file which you can see by doing 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 my script fails?

It fails because I forgot to put blanks between the command and the arguments! Hence the command it though I was interested in was [ns6511.

In fact $HOST, ==, ns6511, ] are the options of [ command.

So insert all missing blanks between the command and its options and all will work as expected.

Finally the correct syntax is obviously as follows:


HOST=`hostname -s`

if [ $HOST == 'ns6511' ]
then
# do somthing
fi


Hope this reminder pleased you and this learning session just proves something important: how Unix -- which, at first sight, could be considered as a deprecated technology of the 70s -- is really not. The answer is probably: simplicity.

And simplicity here means power and evolution.



Back