Tuesday, February 24, 2009

Running a cmd from bash script

Problem:

There are many situations in which you may want to run different command in your shell script depending on requirements and circumstances.

There are two approaches we can take from here on.

Approach #1:

Use either case statement or if..elif..else For example:



#!/bin/bash
if [ this -eq that ];then
command1
else
command2
fi



Approach #2:

BASH allows you to assign/store a command in a built-in variable called CMD. Build your command in this variable and execute $CMD.



#!/bin/bash
[ this -eq that ] && CMD=”/bin/ls” || CMD="/bin/date";
eval $CMD;



This is a very simple example and this approach is very much generic if you want to have a generic function to execute all the commands. For example:



#!/bin/bash

execute() {
# $1 holds the arg to this function
CMD="$1";
eval $CMD;
}

## Here is your main function

if [ this -eq that]
then
execute "/bin/ls | wc -l";
else
execute "/bin/ls";
fi



NOTE: eval is required when you use "|" or redirection of cmd output.

Happy hacking :) !!

No comments:

Post a Comment