How can I preserve new lines coming from a command's output during variable assignment?
7,516
You need to quote your expansion, otherwise it will undergo word splitting, which is what you are experiencing.
acl=$(getfacl somefile.dat)
echo "$acl"
Bear in mind that $(
strips trailing newlines anyway (it is considered a feature). If that is a problem for you, you need to do something like this to preserve them (in bash4+):
mapfile acl < <(getfacl somefile.dat)
printf %s "${acl[@]}"
Related videos on Youtube
Comments
-
Kent Pawar almost 2 years
Consider:
$ getfacl somefile.dat # The output is formatted and contains several new lines.. # file: somefile.dat # owner: user1 # group: group1 user::rw- group::r-- #effective:r-- mask:r-- other:r-- $ $ ACL_PERMISSIONS=$(getfacl somefile.dat); $ echo $ACL_PERMISSIONS; # file: somefile.dat # owner: user1 # group: group1 user::rw- group::r-- #effective:r-- mask:r-- other:r--
So how do I preserve these new lines during variable assignment, so that when I echo
$ACL_PERMISSIONS
I get the same output as$ getfacl somefile.dat
..?-
Kent Pawar about 11 yearsKindly explain the reason for the -1..?
-
clerksx about 11 yearsI'm not the downvoter, but my guess would be that it is because this is an issue merely involving missing quotes (which I don't think warrants a downvote, but I've seen it happen before on questions like this).
-
-
Kent Pawar about 11 yearsHey @Chris, Thanks! I wasn't aware of 'word splitting' and using quotes around the variable does solve my problem.. Just curious, how can I preserve trailing newlines (not sure where such a thing might help) using ksh..?
-
clerksx about 11 years@KentPawar The first method should also work in
ksh
. -
clerksx about 11 years@KentPawar From
help mapfile
: "[r]ead lines from the standard input into an indexed array variable". It essentially reads each line from the output ofgetfacl somefile.dat
into an array calledacl
. -
suspectus about 11 years$( strips newlines ?
list=$(ls); echo $list; echo "$list"
word splitting is demonstrated withecho $list
, if newlines were stripped then I'd expect the same output with the 2nd echo. -
Kent Pawar about 11 years@ChrisDown - thanks. But seems like mapfile does not come bundled with the Linux/Solaris boxes I am working on..
-
suspectus about 11 years@Kent - hmm strange, In ksh just tried the
list=$(ls)
etc (as above) andecho $list
strips newlines,echo "$(list)"
does not. -
suspectus about 11 years@Kent - sorry for confusion. "strips newlines" is not a command it is just text. I think in your case you just need to enclose the variable in quotes as Chris suggested.
-
clerksx about 11 years@suspectus
$(
strips trailing newlines, not just any newlines. -
clerksx about 11 years@KentPawar Just use the first example, in that case.