echo newline character not working in bash

Solution 1:

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'

Solution 2:

The recommended practice is to use printf for all new scripts.

printf '%s\n%s\n' "Hello" "World"

printf '%s\n' "Hello\nWorld"

Solution 3:

When you use bash myfile.sh, Bash is ran in "batch" mode, on a separate process, and does not read its profile or rcfile.

When you use . myfile.sh, the file is sourced by the current shell process (as if its contents were typed by you), therefore it sees your currently defined aliases.

In general, it is a Very Bad Idea to write scripts that depend on any particular shell configuration, especially aliases, unless you define them in the script itself. (Never rely on user's .bashrc, even if it's your own.)

Solution 4:

This works fine in terminal

#!/bin/bash
alias echo="echo -e"
echo "Hello\nWorld"

save to a file and make it exeutable (chmod +x) it

run as ./your_file