How to Use echo in Bash Scripts to Display a New Line [4 Best Ways]

TL;DR

To use echo in Bash scripts for displaying a new line, you can try one of the four following methods:

  1. To use the echo command to create a new line, users can create a new script file, type the desired text using the echo command, save the file, make it executable, and run the script.
  2. The -e option can be added to the echo command to create new lines in the output.
  3. The $'string' syntax can be used to display a new line with text in multiple lines with \n in a string variable.
  4. A variable containing a new line value can also be used with the echo command to get output in different lines.

Alternative methods, such as the printf command and here documents can also be used to create new lines in Bash shell scripts. Additional tips include using the environment variables, understanding escape sequences, and testing scripts thoroughly.

Let’s learn more about how to use the echo command in Bash Shell Scripts to display the New Line from the article below.

Bash is a command-line shell used in Linux and Unix-based operating systems that allows you to automate tasks, create scripts, and perform system-level operations. One common task you may encounter while working with Bash is displaying (or echoing) a new line to improve the readability of your code’s output. To do that, you can try the four ways to display a new line with the echo command in the Bash scripts. Along with that, you can also use the two alternatives and five best practices to optimize this process.

How to Use echo in Bash Scripts to Display a New Line

To use echo in Bash scripts to display a new line, you can try out using the simple echo command to display a new line, -e option, $'string' syntax, or a variable containing the new line (\n) value. Here’s the detailed guide for each of these methods:

1. echo Command

To echo a new line using the echo command in Bash shell scripts, you should follow these steps:

  1. In the command prompt, create a new bash shell script with the touch command:
touch myscript1.sh
  1. Within the Terminal app, open the file by using the nano command:
nano myscript1.sh
  1. Type the following code to create a new line using the echo command in Bash shell scripts:
echo "This is the first line."
echo "This is the second line."
  1. Press Ctrl + O and Enter to save. Then, press Ctrl + X to exit the editor. Then, make the script executable with the command:
chmod +x myscript1.sh
  1. Run the script by entering the following command in the Terminal:
/myscript1.sh
  1. The output should show the two lines, each on a separate line, with a new line character.
basic echo command

2. Use the -e Option

Another way is to add the -e option to echo in Bash scripts to display a new line. Here’s how you can do it:

  1. Use the touch command to create a new file in the Terminal:
touch myscript2.sh
  1. Open the file in a text editor such as nano or vi:
nano myscript2.sh
  1. Type the following code into the file:
#!/bin/bash

echo -eThis is the first line.\nThis is the second line.
  1. Save the file with Ctrl + O and exit the text editor with Ctrl + X.
  2. Make the file executable using the chmod command:
chmod +x myscript2.sh
  1. Run the script using the ./ operator:
./myscript2.sh
  1. The output should be:
echo e command

3. Use the $’string’ Syntax

The use of $'string' syntax lets you echo a new line with multiple lines with \n in a string variable. To do so, follow the steps below:

  1. In the Linux command prompt, execute the following:
echo $'\n'
  1. The Terminal will output a new line character.
echo a new line with multiple lines
  1. Alternatively, you can run the following command:
echo $'This is the first line.\nThis is the second line.'
  1. The Terminal will output:
echo string syntax

4. Use a Variable Containing a New Line

You can also use a variable with the string value and new line special characters to get output in different lines. Here’s how to do it:

  1. In the Terminal app, declare a variable containing a string that includes a new line character:
str="Hello\nworld"
  1. Use the echo command with the -e option to interpret escape sequences, including the new line character:
echo -e $str
  1. The Terminal will display the following output:
variable containing a new line

2 Alternative Ways to Display New Lines in Linux

While echo in Bash scripts is a common and effective method for creating new lines, alternative commands and techniques exist. Some of the most common alternative methods include printf and heredoc. Let’s have a closer on how to use them here:

1. printf Command

printf offers better control over output formatting than echo in Bash scripts. It allows you to format and print data using format specifiers, making it useful for creating new lines and more complex text formatting in Bash shell scripts.

Script File Code:

#!/bin/bash

printf "%s\n" "This is the first line." "This is the second line."

printf "This is the third line.\nThis is the fourth line.\n"

Output:

printf command echo in Bash scripts

2. Here Document (heredoc)

heredoc is a powerful way to create multi-line input for commands. It makes it easy to print multiple lines without using the escape sequences or echo in Bash scripts. They also support variable expansion and command substitution, offering flexibility and versatility for shell scripting.

Script File Code:

#!/bin/bash

cat << 'EOF'

This is the first line.

This is the second line.

This is the third line.

This is the fourth line.

EOF

Output:

heredoc command linux

Quick 5 Tips to Optimize echo in Bash Scripts

Follow these five best practices if you want to optimize the use of echo in Bash scripts and improve your code’s output readability:

  • 🌍 Environment Variables: Use environment variables to store text and data directly in your scripts. It allows for greater flexibility and easier maintenance. Moreover, this approach replaces hard-coding values directly in your scripts, which makes them more adaptable and efficient.
  • 📋 -e Option: Add the -e option with echo in Bash scripts to enable the interpretation of backslash escapes. It makes sure to process the escape sequences like \n correctly and not treat them as plain text.
  • 🔄 Alternative Methods: In some cases where more complex formatting is needed, consider alternative methods like the printf command. This versatile command allows for intricate output formatting and variable inclusion, providing more control over the final output.
  • 📚 Understanding Escape Sequences: Master common escape sequences such as \n (new line), \t (tab), and \e (escape) to create more sophisticated output with echo in Bash scripts. Familiarity with these sequences lets you change output colors or add other formatting effects.
  • 🧪 Test Scripts: Always test your scripts after making changes to ensure accurate output. Thorough testing helps identify potential errors or unexpected results, safeguarding your scripts’ reliability in production environments. Experiment with various inputs and carefully examine the output for any discrepancies.

Final Thoughts

The echo command is a widely used command in Bash shell scripts for displaying output and creating new lines. It can be used in various ways, such as adding the -e option, using the $'string' syntax, or a variable containing a new line character. Alternative methods like printf and heredoc provide more control over output formatting and allow for creating multi-line input for commands.

To expand your proficiency in Bash shell scripting, check out my detailed guide on using set x to debug code, clearing Bash history to protect sensitive information, and running shell scripts in the Bash interpreter. These resources can help you create more structured and manageable Bash scripts within the Linux Terminal, improving your programming skills in Linux.

    Frequently Asked Questions

    What is the difference between print and echo in Bash scripts?

    Both printf and echo in Bash scripts are used to display formatted output. However, printf is more powerful and flexible than echo. This is because printf allows you to format the output using placeholders and control characters while echo does not. For example:
    echo "My name is John, and I am 30 years old." 
    printf "My name is %s, and I am %d years old.\n" "John" 30

    Both commands will output the same string, but printf allows you to specify the format of the output using placeholders (%s for strings, %d for integers, etc.) and control characters (\n for new lines, \t for tabs, etc.).

    Can I use the echo in Bash scripts to write to a file?

    Yes, you can use the echo command in Bash scripts to write to a file. Simply redirect the output of the echo command to a file using the “>>” operator. For example:

    echo "Hello, World!" >> myfile.txt

    This will append the string “Hello, World!” to the end of the file myfile.txt.

    Can I use echo in Bash scripts to redirect output to a file?

    Yes, you can use echo in Bash scripts to redirect the output to a file. To do so, you need to type the output redirection operator > followed by the name of the file. For example, echo Hello, World! > output.txt will write the text “Hello, World!” to a file named output.txt.

    How do I add comments to my Bash script to make it more readable?

    To add comments to your Bash script, you can use the # symbol. Everything following the # symbol on a line is treated as a comment and will not be executed. For example:
    #!/bin/bash
    # This is a comment explaining the purpose of the script
    echo "Hello, World!" # This line prints "Hello, World!" to the terminal

    Adding comments to your script is a good practice, as it helps others (and yourself) understand the purpose and functionality of your code when reviewing it later.

    Are there any limitations to echo in Bash scripts?

    Yes, there are a few limitations to consider when using the echo command in Bash scripts. Firstly, it may not handle special characters or control characters correctly, leading to unexpected output. Secondly, this command has limited control over formatting, making it less suitable for complex formatting requirements. Additionally, it lacks built-in support for variables or expressions, requiring workarounds for their inclusion. It also automatically appends a newline character and doesn’t provide direct file output. To overcome these limitations, alternatives like printf or other specialized tools may be preferred in certain scenarios.

    Total
    0
    Shares