Home > front end >  bash: how to return string with newline from function?
bash: how to return string with newline from function?

Time:04-07

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

CodePudding user response:

Use printf to print formatted strings.

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

CodePudding user response:

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:

  • Related