In this short post, we'll see how to add a new line at the end of Bash output. We will discuss how to add new line to:

  • end of output
  • end of each line
  • add new line to variable
  • output new line to file

The image below summarize the methods described in the article:

How to add a new line in bash

Let's cover multiple examples on - how to add a new line in shell script output?

(1) add new line by echo ""

curl -s "http://example.com" && echo ""

(2) chain commands and write to file

curl -s "https://www.reddit.com/.json" | jq -c . && echo "" >> out.json

(3) Add new line to output variable

output="Hello, World!"
echo -e "${output}\n"

Where:

  • the -e option enables parsing of backslash escapes
  • the \n escape sequence represents a line break

(4) Add new line to output - in the middle

echo -e "first line\second line"

The commands above work for most Unix-like shells such as bash.

We briefly described a few ways to append a line break to the output of a command or variable by using the echo command.

As a bonus we will cover how to write parallel cURL requests, writing to file and appending new lines to the end of each line.

Add new line to output

We will cover multiple ways to add line breaks in loops or parallel writing to a file. So instead of getting:

{"message": "Too Many Requests", "error": 429}{"message": "Too Many Requests", "error": 429}

we will output each result to a new line as:

{"message": "Too Many Requests", "error": 429}
{"message": "Too Many Requests", "error": 429}

add new line by echo and parenthesis

To add new lines in script while using for loop or seq parallel command we can use parenthesis: (xargs -I{} -P2 -- curl -s "https://www.reddit.com/.json" && echo "")

#!/bin/sh
for i in `seq 2`;
    do seq 1 1 | (xargs -I{} -P2 -- curl -s "https://www.reddit.com/.json" && echo "") >> data.json & sleep 3
done

append new line with JQ

For JSON output we can use commands like jq in order to append a new line - jq -c .

#!/bin/sh
for i in `seq 4`;
    do seq 1 2 | xargs -I{} -P2 -- curl -s "https://www.reddit.com/.json" | jq -c . >> ~/data.json & sleep 3
done

Note: to split each JSON value to new line we can use: jq -c '.[]':

429
"Too Many Requests"
429
"Too Many Requests"
429
"Too Many Requests"
429

Note 2: Both ways will add a new line to the end of each output from the cURL command. If we try to use direct writing we will get all outputs to the same line:

#!/bin/sh
for i in `seq 2`;
    do seq 1 1 | xargs -I{} -P2 -- curl -s "https://www.reddit.com/.json" >> data.json & sleep 3
done

Conclusion

In this article we covered questions like:

  • How do I add a new line to the end of output in bash?
  • How do I add a new line in bash?
  • How do you add a new line in shell script output?
  • Does echo append a newline?
  • How do I append to the end of a file in bash?
  • How do you add a line break in a string?
  • What is \n in bash?