I want to put the result of a command in a variable without ignoring \n
$cmd=$(ls -l)
echo $cmd
CodePudding user response:
There's probably a higher level solution to your actual problem, but if you really want to keep the trailing newlines, you could do something like:
a=$(ls -l; echo .)
a=${a%.}
but it seems like a terrible hack.
CodePudding user response:
In general, you should only use ls via substitution or in scripts, if you are willing to guarantee that none of your file names contain either spaces or special/control characters. I am, but most people are not, and they will probably tell you not to use ls non-interactively at all.
The ls command works via whitespace seperated fields. It is a very old convention, and while it works well enough if you are willing to be loyal to it, as mentioned, most contemporary users are not. As a result, using it in scripts when you have spaces in filenames will cause hazardous and/or unpredictable results.
CodePudding user response:
Use double quotes for variable substitution and command substitution:
cmd="$(ls -l)"
echo "$cmd"
See this page for further information.