The True Story of Unix Shell 'IF'
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/[
[ 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
] are the options of
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.