Print new line linux

How to echo a New Line in Bash Shell Scripts

Learn various ways of displaying a new line in the output of echo command in Linux.

The echo command automatically adds a new line at the end. That’s cool.

But what if you want to display just an empty new line? Or if you want to output something that contains a new line?

The good news is that, echo lets you use the newline character \n to print a new line within the same output line if you use the -e option:

echo -e "Name\nAddress\nPhone Number"

If you run the above command, you’ll get this output:

Name Address Phone Number

That’s nice, right? Let’s have a more detailed look into it.

Display new line with -e flag of echo command (recommended)

A newline is a term we use to specify that the current line has ended and the text will continue from the line below the current one. In most UNIX-like systems, \n is used to specify a newline. It is referred to as newline character.

The echo command, by default, disables the interpretation of backslash escapes. So if you try to display a newline using the ‘\n’ escape sequence, you will notice a problem.

$ echo Hello\nworld Hellonworld $ echo 'Hello\nworld' Hello\nworld

Enclosing text in single quotes as a string literal does not work either.

That was not an expected output. To actually print a new-line, you can use the ‘-e’ flag to tell the echo command that you want to enable the interpretation of backslash escapes.

$ echo -e 'Hello\nworld' Hello world

Nice, that’s what you are looking for.

Let me some other ways to display the newline character.

echo a variable containing new line

You can store a string in a bash variable and then echo it using the ‘-e’ flag.

$ str="Hello\nworld" $ echo -e $str Hello world

Use the ‘$’ character instead of -e flag

The dollar symbol, ‘$’ is called the «expansion» character in bash. This is the character that I used in the earlier example to refer to a variable’s value in shell.

If you look closely at the snippet below, you will realize that the expansion character, in this case, acts to hold a temporary value.

$ echo Hello$'\n'world Hello world

Or, you can use the whole string as a ‘temporary variable’:

$ echo $'Hello\nworld' Hello world

I would prefer to use the -e flag, though.

echo your echo to print something with new line

When you echo a piece of text, the echo command will automatically add a newline (and here is how you can prevent it) to the end of your text.

This means that you can chain multiple echo commands together to cause a newline.

$ echo Hello; echo world Hello world

Use printf to print newline in Bash shell

printf is another command line tool that essentially prints text to the terminal, but it also allows you to format your text.

Читайте также:  How to get user name linux

The usage is very simple and similar to echo but a bit more reliable and consistent.

$ printf 'Hello\nworld\n' Hello world

As expected, you have a newline without using any flags.

Conclusion

Personally, I would prefer sticking with the -e flag or go for the printf command for displaying the new lines in output. I recommend you to do the same but feel free to experiment.

Источник

How to Echo Newline in Bash

In Bash, there are multiple ways we can display a text in the console or terminal. We can use either the echo or printf command to print a text. Each of these commands has their unique behaviors.

In this guide, we’ll learn how to print a newline in Bash.

Newline in Bash

Before going further, here’s a quick refresh on what a newline is. It’s usually used to specify the end of a line and to jump to the next line. It’s expressed with the character “\n” in UNIX/Linux systems. Most text editors will not show it by default.

Printing Newline in Bash

There are a couple of different ways we can print a newline character. The most common way is to use the echo command. However, the printf command also works fine.

Using the backslash character for newline “\n” is the conventional way. However, it’s also possible to denote newlines using the “$” sign.

Printing Newline Using Echo

The echo command takes a string as input and prints it out on the console screen. To print any text, we use the echo command in the following manner:

As mentioned earlier, the newline character is “\n”, right? How about we try to include it directly with echo?

Well, that didn’t go as expected. What happened?

By default, the echo command will print the string provided, character by character. It doesn’t interpret backslash characters. However, we can fix this by adding the flag “-e”. It enables backslash character interpretation. Let’s fix the command and run it again:

Voila! Now it’s working as expected!

This technique also works when using Bash variables. Take a look at the following example:

$ sentence = «The \n Quick \n Brown \n Fox»

Printing Newline Using $

We can also use the “$” sign with the echo command to specify the newline character. This method is a bit more complex than the previous one. The explanation is best done with an example.

Run the following command:

  • The given string isn’t inside double quotations.
  • Before each newline character “\n”, we’re using the “$” sign.
  • Each newline character “\n” is provided inside single quote.

Printing Newlines with Multiple Echo Statements

In this approach, we’re basically going to run multiple echo commands instead of one. By default, echo prints the given string and adds a newline character at the end. By running multiple echo statements at once, we’re taking advantage of that.

Let’s have a look at the following example.

  • We’re running 4 echo commands.
  • Each command is separated by a semicolon (;). It’s the default delimiter in Bash.

Printing Newline with Printf

Similar to echo, the printf command also takes a string and prints it on the console screen. It can be used as an alternative to the echo command.

Have a look at the following example.

As you can see, printf processes backslash characters by default, no need to add any additional flags. However, it doesn’t add an additional newline character at the end of the output, so we have to manually add one.

Читайте также:  Install kerio on linux

Final Thoughts

In this guide, we’ve successfully demonstrated how to print newlines in Bash. The newline character is denoted as “\n”. Using both the echo and printf commands, we can print strings with new lines in them. We can also cheat (well, technically) by running the same tool multiple times to get the desired result.

For more in-depth info about echo and printf, refer to their respective man pages.

Interested in Bash programming? Bash is a powerful scripting language that can perform wonders. Check out our Bash programming section. New to Bash programming? Get started with this simple and comprehensive guide on Bash scripting tutorials for beginners.

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.

Источник

How can I print a newline as \n in Bash?

Basically, I want to achieve something like the inverse of echo -e . I have a variable which stores a command output, but I want to print newlines as \n.

Strictly speaking, the inverse of echo -e would also involve translating additional control chars. into their escape sequences, such as tabs to ‘\t’ . Based on the accepted answer, however, it seems that handling newlines is sufficient in this case.

4 Answers 4

+1 — clever; as with the awk solution, you always get a trailing literal \n sequence; unlike with awk , however, suppressing it is simple: sed ‘$! s/$/\\n/’ .

If your input is already in a (Bash) shell variable, say $varWithNewlines :

It simply uses Bash parameter expansion to replace all newline ( $’\n’ ) instances with literal ‘\n’ each.

If your input comes from a file, use AWK:

In action, with sample input:

# Sample input with actual newlines created with ANSI C quoting ($'. '), # which turns `\n` literals into actual newlines. varWithNewlines=$'line 1\nline 2\nline 3' # Translate newlines to '\n' literals. # Note the use of `printf %s` to avoid adding an additional newline. # By contrast, a here-string -  
  • awk reads input line by line
  • by setting ORS - the output record separator to literal '\n' (escaped with an additional \ so that awk doesn't interpret it as an escape sequence), the input lines are output with that separator
  • 1 is just shorthand for , i.e., all input lines are printed, terminated by ORS .

Note: The output will always end in literal '\n' , even if your input does not end in a newline.

This is because AWK terminates every output line with ORS , whether the input line ended with a newline (separator specified in FS ) or not.

Here's how to unconditionally strip the terminating literal '\n' from your output.

# Translate newlines to '\n' literals and capture in variable. varEncoded=$(printf %s "$varWithNewlines" | awk -v ORS='\\n' 1) # Strip terminating '\n' literal from the variable value # using Bash parameter expansion. echo "$" 

By contrast, more work is needed if you want to make the presence of a terminating literal '\n' dependent on whether the input ends with a newline or not.

# Translate newlines to '\n' literals and capture in variable. varEncoded=$(printf %s "$varWithNewlines" | awk -v ORS='\\n' 1) # If the input does not end with a newline, strip the terminating '\n' literal. if [[ $varWithNewlines != *$'\n' ]]; then # Strip terminating '\n' literal from the variable value # using Bash parameter expansion. echo "$" else echo "$varEncoded" fi 

Источник

In Bash, a new line refers to the end of a line of text and the beginning of a new one. When a command is executed in Bash, the output is often displayed on the terminal with each line of text ending in a new line. The new line character is represented by a special escape sequence, \n , which tells the terminal to move the cursor to the beginning of the next line.

Printing a newline in Bash is important because it helps to format the output in a way that is easy to read and understand. For example, if you are printing the results of a command that produces a lot of output, using new lines can make it easier to parse the information. Additionally, new lines can be used to visually separate different sections of output, making it easier to locate specific information.

In this article, we'll take a look at several different ways to print a new line, including using the echo command with the -e option, the printf command, and the escape sequence \n .

Two Ways to Print a NewLine in Bash

Here are several different ways to print a newline in Bash. In this section we'll take a look at two most common.

Using the echo command with the "-e" option

The echo command is used to display a message or output on the Bash. It is often used to print a string of text, but it can also be used to print the value of a variable or the output of a command.

The echo command has a number of options that allow you to customize its behavior. The one we are interested in is the -e option, which allows you to use escape sequences to include special characters in the output.

That specific option enables us to use the \n special character to print a newline in Bash:

echo -e "This is the first line\nThis is the second line" 
This is the first line This is the second line 

Using the printf command

In Bash, the printf command is used to display a message or output in the terminal. It is similar to the echo command, but it is generally more powerful and flexible, and it is often preferred over echo for formatting and printing output in Bash scripts.

Like echo , printf can be used to print a string of text, the value of a variable, or the output of a command. However, printf also allows you to specify a format string, which allows you to control the appearance of the output in more detail.

Therefore, there is no need to use any special options/flags (like -e ), just write the string format between two quotation marks:

printf "This is the first line\nThis is the second line" 

As expected, this will yield us with:

This is the first line This is the second line 

Note: In all of these examples, the \n escape sequence is used to represent a new line. The echo and printf commands are used to print the text to the terminal, and the -e option for echo allows it to interpret the escape sequences.

Conclusion

In conclusion, writing a new line in Bash is an important task that allows you to format the output of your scripts and commands in a way that is easy to read and understand. In this article, we covered two most common ways to write a new line in Bash - using the echo command with the -e option, and the printf command.

Источник

Оцените статью
Adblock
detector