'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
Solution 1:[1]
Use printf to print formatted strings.
create_string() {
printf '[%s]\nworld\n' "$1"
}
Solution 2:[2]
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:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
| Solution 2 |
