How to insert a new line in Linux shell script?

LinuxBashNewline

Linux Problem Overview


I want to insert a new line between multiple echo statements. I have tried echo "hello\n", but it is not working. It is printing \n. I want the desired output like this:

Create the snapshots

Snapshot created

Linux Solutions


Solution 1 - Linux

The simplest way to insert a new line between echo statements is to insert an echo without arguments, for example:

echo Create the snapshots
echo
echo Snapshot created

That is, echo without any arguments will print a blank line.

Another alternative to use a single echo statement with the -e flag and embedded newline characters \n:

echo -e "Create the snapshots\n\nSnapshot created"

However, this is not portable, as the -e flag doesn't work consistently in all systems. A better way if you really want to do this is using printf:

printf "Create the snapshots\n\nSnapshot created\n"

This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n at the end, as printf doesn't append a newline automatically as echo does.

Solution 2 - Linux

Use this echo statement

 echo -e "Hai\nHello\nTesting\n"

The output is

Hai
Hello
Testing

Solution 3 - Linux

echo $'Create the snapshots\nSnapshot created\n'

Solution 4 - Linux

You could use the printf(1) command, e.g. like

printf "Hello times %d\nHere\n" $[2+3] 

The  printf command may accept arguments and needs a format control string similar (but not exactly the same) to the one for the standard C printf(3) function...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3086014View Question on Stackoverflow
Solution 1 - LinuxjanosView Answer on Stackoverflow
Solution 2 - LinuxKalanidhiView Answer on Stackoverflow
Solution 3 - LinuxOhad CohenView Answer on Stackoverflow
Solution 4 - LinuxBasile StarynkevitchView Answer on Stackoverflow