user3108468
user3108468

Reputation: 63

bash: how to return string with newline from function?

I need to save the following in a file using function.

[hello]
world

I try a couple of ways but none works.

#!/bin/bash


create_string() {
  str="[${1}]\n"
  str="${str}world\n"
  echo $str
}

create_string hello >> string.txt

The file is like this.

[hello]\nworld\n

Upvotes: 0

Views: 910

Answers (2)

Stephen Quan
Stephen Quan

Reputation: 26379

When it comes to multiline output, I like to use cat with a here document with EOF as the delimiting identifier, e.g.

#!/bin/bash

create_string() {
    cat <<EOF
[$1]
world
EOF
}

create_string hello >> string.txt

Which creates string.txt with the newline markers required:

$ od -c string.txt
0000000    [   h   e   l   l   o   ]  \n   w   o   r   l   d  \n        
0000016

References:

Upvotes: 2

Barmar
Barmar

Reputation: 782785

Use printf to print formatted strings.

create_string() {
    printf '[%s]\nworld\n' "$1"
}

Upvotes: 6

Related Questions