1. Overview
In many cases, we need to add a new line in a sentence to format our output. In this tutorial, we’ll explore some Linux commands for printing a new line character (\n) in a sentence.
2. Using echo
The echo command is one of the most commonly used Linux commands for printing to standard output:
$ echo "test statement \n to separate sentences"
test statement \n to separate sentences
By default, echo considers \n as a regular part of the input string. So, to enable the echo command to interpret the new line character, we should use the -e option:
$ echo -e "test statement \n to separate sentences"
test statement
to separate sentences
Note echo adds \n at the end of each sentence by default whether we use -e or not.
The -e option may not work in all systems and versions. Some versions of echo may even print -e as part of their output. Therefore, we can say that echo is not portable unless we omit flags and escape sequences, which is useless in this case. So, a better way to apply\n will be using printf.
3. Using printf
The printf command is also for printing our sentence to standard output:
$ printf "test statement \n to separate sentences"
test statement
to separate sentences $
Unlike echo, printf* doesn’t need an option to enable interpreting *\n in our sentence. So, the new line character will be applied to the sentence by default.
Note that unlike echo, printf won’t add \n at the end of each sentence automatically. The $ at the end of the result is because of that. Therefore, we need to add \n at the end of each line, manually:
$ printf "test statement \n to separate sentences \n"
test statement
to separate sentences
printf will work in all systems. Notice that a disadvantage of printf is its performance. The built-in shell echo is much faster. So, choosing one is a trade-off between portability and performance. printf can basically do what the C version of it can do. So, we have the advantage of formating input strings.
4. Using $
Since bash 2, words of the form $’string’ are treated specially. All the backslash-escaped characters will be applied to sentences. So, we can use this format with echo and printf:
$ echo $'test statement \n to separate sentences'
test statement
to separate sentences
We use echo because printf interpreted \n by default. Note that we should use single quotes to cover the input string. Double quotes won’t work.
5. Conclusion
In this article, we’ve described how we can add \n to our output.
First, we used echo, and then we user printf, which is a more reliable command for adding backslash-escaped characters. In the end, we introduce $’string’ format that will replace backslash-escaped characters based on the ANSI C Standard.