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.
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012
- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop