Anita
Anita

Reputation: 23

How can I create a line break on Bash while responding to a prompt?

I'm creating a README file using Bash. When adding description in the file, I want the text to appear as 2 paragraphs. How can I create a line break after para one? I tried "\n" but nothing happened.

Upvotes: 1

Views: 129

Answers (1)

David C. Rankin
David C. Rankin

Reputation: 84561

Continuing from my comments. What you want to be able to write formatted blocks of text out to a file (or to the terminal /dev/stdout) is a heredoc. A heredoc will write the lines out as formatted between and opening and closing tag. (EOF is traditionally used, but it can be anything you like). The form is:

cat << EOF
  Your text goes here
  and here

  and here, etc...
EOF

If you want to write to a file, then use cat >filename << EOF as the opening. If you have variables in your text that you do not want expanded (e.g. $myvar you want written out as $myvar and not what it holds), quote the opening tag, e.g. 'EOF')

In your case if you want to write to a filename from within your script, then just use the form above. You can use default initialization to write to the terminal if no filename is given as an argument to your script, e.g.

#!/bin/bash

fname="${1:-/dev/stdout}"    # set filename to write to (stdout by default)

# heredoc
cat >"$fname" << EOF

  My dog has fleas and my cat has none. Lucky cat. My snake has
scales and can't have fleas. Lucky snake.

  If the animals weren't animals could they still have fleas?

EOF

If called with no argument, the heredoc is printed to the terminal (/dev/stdout). If given a filename, then the heredoc output is redirected to the filename, e.g.

$ bash write-heredoc.sh README

Fills the README file with the heredoc contents, e.g.

$ cat README

  My dog has fleas and my cat has none. Lucky cat. My snake has
scales and can't have fleas. Lucky snake.

  If the animals weren't animals could they still have fleas?

You can include blank lines as you like. If you want to append to your README file using multiple heredocs, then just use cat >>filename << EOF to append instead of truncate.

Upvotes: 3

Related Questions