Bash shell script tip: Run commands from a variable

by Vivek Gite on April 22, 2007 · 15 comments

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:
/path/to/backup.sh nas
/path/to/backup.sh tape
/path/to/backup.sh scp

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.

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

We're here to help you make the most of sysadmin work. So, subscribe!

{ 15 comments… read them below or add one }

1 Bruno April 24, 2007

It would be nice to write just 2 lines about the way it works : (condition-A && condition-B) : bash evaluate condition-B only if condition-A is true. If condition-A is false, the result is FALSE anyway and bash doesn’t need to evaluate condition-B. Then it goes thru all the || conditions.
Or point to a page that explain this.
Anyway, it is very nice to be able to read these tips on a regular basis.
Thanks

Reply

2 Mahesh May 4, 2007

Hi

I want to take tar-backup of user home folders on RH9 Linux.

My short script is as follows :

#!/bin/bash
#pwd
cd /home
tar cvzf /backup/archive/usr1-`date +%C%y%m%d`.tar.gz usr1
tar cvzf /backup/archive/usr2-`date +%C%y%m%d`.tar.gz usr2
.
.
So On !!!!!!!!!

If i am running this script from cmd , it works fine. But If i cron the job it stops aborted on 2nd directory itself with half-completed tar file.
How to solve this problem? I am not so novice in Linux. Pls help.

Regards /Mahesh

Reply

3 raihan September 22, 2007

can you guys please send me linux shell script commands for backup documents home folder, i need it
very badly because i need to submit it on 24/9/07 to my teacher..please any one kindly send me this..
my e-mail address raihan_alam@hotmail.com

Reply

4 corex December 8, 2007

I experienced another problem.
If I call script files, input methods (read ) are ignored.

find /media/private -iname "*.bash" | while read file
do
echo "Executing: $file"
$file -m
if [ "$?" -ne 0 ]
then
echo "Error executing $file"
exit 1
fi

echo "done"

Reply

5 Finnbarr Murphy March 24, 2008

This is not just a bash feature as you imply. $CMD works with Korn shell and most other shells.

Reply

6 charusrinivasan April 2, 2009

hai i want a example linux program for case statement

Reply

7 pavium April 22, 2009

It may be slightly more clever to use variables this way, but what are we sacrificing? READABILITY.

You’ll be sorry when to look at the script a few months from now.

Reply

8 kalem December 14, 2009

hi, i am trying to make a precess to run by itself whenever a media is plugged.
the process finds and eliminate (deletes) programs ,viruses .
since i use UNIX/lunix , these programs don’t run on my machine.
can any one say some ?
thanks in advance

Reply

9 Hanish May 17, 2010

if I give a PIPE to a command then it does not work like

CMD=’ps -ef|grep vnc’

Help me out…

Reply

10 Hanish May 17, 2010

Hi investigated and eval did a trick.

CMD=’ps -elf|grep vnc’
eval $CMD

Thanks to all

Reply

11 dev May 10, 2011

Hi,

I am trying to execute some list of commands.So,I have added my commands inside a csv file.I am trying to read that command and execute the command and store the result of the command in the variable.

cmd=`echo $line | awk -F ‘;’ ‘{print $1}’`
After this “cmd” gets the value like “cat filename | wc -l ”

I am trying to store in a variable like this
count=`$cmd`.

Since there is a pipe i am getting error.
Can some one help me on this

Reply

12 Rhongomiant November 17, 2011

dev,

cmd=`echo $line | awk -F ‘;’ ‘{print $1}’`
count=`$cmd`

The variable cmd is storing the results of a command because you have the command encapsulated by backticks “. Based on this information it seems like you are doubling your work. I would modify as follows.

cmd=`echo $line | awk -F ‘;’ ‘{print $1}’`
count=”$cmd”

or

count=`echo $line | awk -F ‘;’ ‘{print $1}’`

If you really need it setup this way, use double or single quotes to encapsulate the command defined by cmd.

cmd=”echo $line | awk -F ‘;’ ‘{print $1}’”

I have not had luck storing commands that contain awk in a variable and calling it later. I usually use a function.

cmd () {
echo $line | awk -F ‘;’ ‘{print $1}’
}

count=`cmd`

Reply

13 dev May 10, 2011

Hanish,

You did a great investigation man. My problem also solved

by giving like this count =`eval $cmd`

Thanks a lot hanish

Reply

14 samira October 2, 2011

Hanish May 17, 2010
Hi investigated and eval did a trick.

CMD=’ps -elf|grep vnc’
eval $CMD

Thanks to all

————————–
thankss soooo muccchhhhhhhh it is workeed

Reply

15 Petridish January 25, 2012

I’m a bit new to linux scripting, but I come from a programming background (c/c++). Out of curiosity, is there a different scripting language besides bash? The syntax is horrible, and I find it incredibly difficult to use.

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 10 + 11 ?
Please leave these two fields as-is:
Are you a human being? Solve the simple math so we know that you are a human and not a bot.



Previous post:

Next post: