There are many situations in which you may want to run different command in your shell script depending on requirements and circumstances. So how do you select and run a command?
The old way...
The old way is use the case statement or if..else..fi command. For example:
#!/bin/bash if [ this -eq that ];then command1 else command2 fi
The new way...
BASH allows you to assign or store a command name in a variable. For example create a variable called CMD:
#!/bin/bash [ this -eq that ] && CMD=”/bin/ls” || CMD="/bin/date" $CMD
Above shell script is a simple example of this concept. CMD variable stores /bin/ls or /bin/date command. To run command you simply type a variable name. So you are using contents of a variable to run command itself depending on circumstances. For example write a backup script to backup data to tape, NAS/ftp server or using scp command. You can run a script as follows:
Now depend upon circumstances you need to swap a command for backup task. Here is a sample script:
#!/bin/bash CMD="" DIRS="/etc /home /www /data1 /data2 /var/log /var/spool/mail" FILE="/backup/$(hostname)-$(date +'%m-%d-%y').tar.gz" [ "$1" == "nas" ] && CMD="lftp -u user,password -e 'cd /dump/; mput /backup/*; quit' nas.mylan.com" || : [ "$1" == "scp" ] && CMD="scp /backup/* scponly@dumpserver:incoming' username" || : [ "$1" == "tape" ] && CMD='tar -cf /dev/st0 /backup/*' || : [ "$CMD" == "" ] && exit 1 || : # make a backup tar -zcvf $FILE $DIRS # Now depend upon circumstances run a backup command $CMD
Now you can run a different backup command in your script depending on parameter passed to script itself. You can also use this trick to write a cross platform shell script.