In a shell script I tried to replace blank space by \n with this command

echo -e $var |tr ' ' '\n'

Outside the script it workd perfectly but inside there is no effect . This how i use in the script:

var =$(echo -e $var | tr ' ' '\n' )

Thanks .


After expanding a parameter expansion ($var) or command substitution ($(cmd)), the shell removes all whitespace from the expanded result in order to split them into words (word splitting). On top of that, it tries to match filenames for the words that contain *, ? and/or [...] (pathname expansion). So always enclose expansions in double quotes ("$var" and "$(cmd)") to avoid word splitting and pathname expansion to be attempted.

$ var=$'two\nlines   here'
$ echo $var
two lines here
$ echo "$var"
lines   here


echo "$var" | tr ' ' '\n'
# or using bash's more powerful types of parameter expansions
echo "${var// /$'\n'}"

var="$(echo "$var" | tr ' ' '\n')"

See also: http://mywiki.wooledge.org/Quotes


From the Bash manual (man bash):

Command substitution allows the output of a command to replace the command name. There are two forms:




Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.

That's why the newline characters are lost.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.