How to store a command in a variable in a shell script?

Benjamin picture Benjamin · Apr 11, 2011 · Viewed 190.3k times · Source

I would like to store a command to use at a later period in a variable (not the output of the command, but the command itself)

I have a simple script as follows:

command="ls";
echo "Command: $command"; #Output is: Command: ls

b=`$command`;
echo $b; #Output is: public_html REV test... (command worked successfully)

However, when I try something a bit more complicated, it fails. For example, if I make

command="ls | grep -c '^'";

The output is:

Command: ls | grep -c '^'
ls: cannot access |: No such file or directory
ls: cannot access grep: No such file or directory
ls: cannot access '^': No such file or directory

Any idea how I could store such a command (with pipes/multiple commands) in a variable for later use?

Answer

Erik picture Erik · Apr 11, 2011

Use eval:

x="ls | wc"
eval "$x"
y=$(eval "$x")
echo "$y"