What Is Echo N in Bash Scripting?

//

Heather Bennett

What Is Echo N in Bash Scripting?

The echo command is commonly used in bash scripting to display text or variables on the terminal. It is a versatile tool that helps in providing feedback, generating output, and displaying information to the user.

One of the options available with the echo command is the -n flag. The -n flag allows you to suppress the trailing newline character that is automatically added by default.

By default, when you use the echo command without any options, it adds a newline character at the end of the output. This means that each time you use echo, it automatically moves to a new line after displaying your desired text or variable.

However, there are situations where you might want to prevent this behavior and keep the cursor on the same line as your output. This is where the -n flag comes into play.

For example:

$ echo "Hello"
Hello
$ echo -n "Hello"
Hello$

In the first example, without using the -n flag, “Hello” is displayed followed by a new line. In the second example, with the -n flag, “Hello” is displayed without a new line.

This can be particularly useful when you want to display multiple pieces of information on a single line or create dynamic progress bars and status updates in your scripts.

Let’s say we want to create a simple progress bar using echo and sleep commands:

#!/bin/bash

echo -n "Progress: "
for (( i=1; i<=10; i++ ))
do
    echo -n "$i "
    sleep 1
done

echo ""
echo "Process complete!"

In this script, we use a for loop to iterate from 1 to 10. With each iteration, we use echo -n to display the value of i without a new line.

Then, we introduce a one-second delay using the sleep command. After ten iterations, we add a new line and display "Process complete! ".

The output will be:

Progress: 1 2 3 4 5 6 7 8
Process complete!

As you can see, the progress bar is displayed on the same line while each number appears sequentially.

In conclusion, the -n flag in the echo command allows you to suppress the newline character that is automatically added. This can be useful in situations where you want to keep output on the same line or create dynamic displays such as progress bars or status updates in your bash scripts.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy