I store the command in a variable cmd
, and get the output of the command using this statement:
echo `$cmd`
everything works fine except ls -l
, the newline is missing.
I store the command in a variable cmd
, and get the output of the command using this statement:
echo `$cmd`
everything works fine except ls -l
, the newline is missing.
If you've stored a command in a string variable, then to run it you need
eval "$cmd"
Running $cmd
only works if the command doesn't contain any shell special characters other than whitespace. Storing a command in a string variable is a bad idea in general. It would be better to define a function:
cmd () {
ls -l
}
Then you can run it with just cmd
.
Your most immediate problem is that you further mangle the output of the command, because you're using an unquoted command substitution. You need to use double quotes around variable and command substitutions. With cmd
defined as a function:
echo "`cmd`"
To avoid surprises with complex commands, use dollar-parenthesis instead of backticks:
echo "$(cmd)"
See Why does my shell script choke on whitespace or other special characters? for explanations.
cmd='cd / && ls -l'
, eval "$cmd"
works and plain $cmd
not work.
– Divlaker
Jun 05 '17 at 06:23
sh -c "$cmd"
– Divlaker Jun 03 '17 at 01:30echo "$(cmd)"
what you wanted? You could just use$cmd
instead. – Michael Homer Jun 03 '17 at 01:31$cmd
is weired, like a variable declaration, but it also works. – Divlaker Jun 03 '17 at 01:37echo
sees all the output as if it was just one long line of arguments as inecho arg1 arg2 arg3 ... argn
. Another way to show this is to do the following. Executeseq -w 1 10
. Then executeecho $(seq -w 1 10)
. – Deathgrip Jun 03 '17 at 02:58