简体   繁体   中英

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

Use printf to print formatted strings.

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

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

#!/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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM