0

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.

Divlaker
  • 123
  • @MichaelHomer Thank you, I tried, but it didn't work. However, I found a solution, using sh -c "$cmd" – Divlaker Jun 03 '17 at 01:30
  • Oh. Is echo "$(cmd)" what you wanted? You could just use $cmd instead. – Michael Homer Jun 03 '17 at 01:31
  • @MichaelHomer, just use $cmd is weired, like a variable declaration, but it also works. – Divlaker Jun 03 '17 at 01:37
  • @Divlaker, the context of what you are trying to accomplish with the output of the command may be helpful as well. You need to understand the relationship with echo and $IFS. In your example echo sees all the output as if it was just one long line of arguments as in echo arg1 arg2 arg3 ... argn. Another way to show this is to do the following. Execute seq -w 1 10. Then execute echo $(seq -w 1 10). – Deathgrip Jun 03 '17 at 02:58

1 Answers1

1

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.