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

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?



Read more here: https://stackoverflow.com/questions/5615717/how-to-store-a-command-in-a-variable-in-a-shell-script

Content Attribution

This content was originally published by Benjamin at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: