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.