Bash shell script tip: Run commands from a variable

Posted on in Categories Howto, Linux, Shell scripting, Tips, UNIX last updated April 22, 2007

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 command. For example:

if [ this -eq that ];then

The new way…

BASH allows you to assign or store a command name in a variable. For example create a variable called CMD:

[ this -eq that ] && CMD=”/bin/ls” || CMD="/bin/date"

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/ nas
/path/to/ tape
/path/to/ scp

Now depend upon circumstances you need to swap a command for backup task. Here is a sample script:

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'" || :
[ "$1" == "scp" ] && CMD="scp /backup/* [email protected]: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

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.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

26 comment

  1. 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.

  2. Hi

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

    My short script is as follows :

    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

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

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

    echo "done"

  4. 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

  5. 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

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

    1. dev,

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

      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=`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}’


  6. 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

  7. 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.

  8. Hi,

    I am trying to execute command (in ksh) stored in varialbe and want to capture output in second variable. For eg,

    var1=”ls -l $RMD_REPORTS/nat_logs/*${REPORT_DATE}*.xml 2>/dev/null | awk ‘{print $NF}'”;
    var2=`eval $var1`;
    echo $var2

    I was expecting only file names as output of above command, however “awk” filter in above command is not working and output of “echo” is same as “ls -l” command. Can anyone tell what’s wrong in above commands?

    1. Sanket,

      I believe you need to escape the $ in the awk statement, so $NF. This works for bash, but I do not know ksh.

      var1=”ls -l $RMD_REPORTS/nat_logs/*${REPORT_DATE}*.xml 2>/dev/null | awk ‘{print $NF}’”;

  9. Lakshmi,

    Given the very general nature of your question, it is impossible for anyone to provide you with helpful information. We need to know what you are doing, why you can’t use export, etc. Basically you are asking how you can call someone in a different area code without entering the area code. You can’t call them, but if you use the same central repository, twitter, facebook, etc. you can share information. If you can’t use export and using the source option will not work then you need a central repository for information shared between scripts. This could be a file, a database, etc.

  10. If I understand your Q right, say you are executing from within and like to use the variables set in Then you need to source from within

    #———–in —————–
    . ./
    #now all variables set in will be available here

  11. Hi All,

    My Condition is like below.. Could any one help on pls ?
    SEARCH=”find `pwd` -name”
    $SEARCH resources.xml | grep $SEARCH_DIR | grep $1 | grep ‘cells’
    but am not getting the pwd as i mentioned in that variable.
    pls help

Leave a Comment