I am trying to use a newline in bash. I found that I need ANSI C quoting for that (i.e. $'\n'), but this often does not work for me. So I am wondering what I am doing wrong.

# This works
>> echo $'a\nb\nc'

# This doesn't 
>> A=$'a\nb\nc'
>> echo $A
a b c 

# Also, this does not work
>> A="a b c"
>> echo ${A// /$'\n'}
a b c 

If I use tab instead of newline, I have the same problems. Other ANSI C quoting work like \', or \", or even \b.

GNU Bash; version: 4.3.11(1)


Because you've not quoted the variable in:

echo $A

it is subject to splitting and globbing. The first step is the expansion of the variable's contents:

echo a $'\n' b $'\n' c -- where the $'\n' bits represent actual newlines.

Then, the various pieces are split on $IFS, resulting in:

echo a b c

Then, since there are no wildcards to generate additional filenames, the strings are passed on to echo.

When you quote the variable, with echo "$A", you inhibit splitting and globbing.

See the change yourself if you modify IFS:

echo $A

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.