Linux – echo newline character not working in bash

bashlinuxscriptshell

I have bash script which has lots of echo statements and also I aliased echo to echo -e both in .bash_profile and .bashrc, so that new lines are printed properly for a statement like echo 'Hello\nWorld' the output should be

Hello
World

but the output I am getting is

Hello\nWorld

I even tried using shopt -s expand_aliases in the script, it doesn't help

I am running my script as bash /scripts/scriptnm.sh; if I run it as . /scripts/scriptnm.sh I am getting the desired output…

Best Answer

The mixed history of echo means its default operation varies from shell to shell. POSIX specifies that the result of echo is “implementation-defined” if the first argument is -n or any argument contains a backslash.

It is more reliable to use printf (either as a built-in command or an external command) where the behavior is more well defined: the C-style backslash escapes and format specifiers are supported in the format string (the first argument).

printf 'foo\nbar\n'
printf '%s\n%s\n' foo bar

You can control the expansion of backslash escape sequences of bash’s echo built-in command with the xpg_echo shell option.

Set it at the top of any bash script to make echo automatically expand backslash escapes without having to add -e to every echo command.

shopt -s xpg_echo
echo 'foo\nbar'
Related Question