bash: 如何从函数 return 带换行符的字符串?
bash: how to return string with newline from function?
我需要使用函数将以下内容保存在文件中。
[hello]
world
我尝试了几种方法,但 none 有效。
#!/bin/bash
create_string() {
str="[]\n"
str="${str}world\n"
echo $str
}
create_string hello >> string.txt
文件是这样的
[hello]\nworld\n
当涉及到多行输出时,我喜欢将 cat
与带有 EOF
作为定界标识符的此处文档一起使用,例如
#!/bin/bash
create_string() {
cat <<EOF
[]
world
EOF
}
create_string hello >> string.txt
创建 string.txt
需要换行符:
$ od -c string.txt
0000000 [ h e l l o ] \n w o r l d \n
0000016
参考文献:
使用printf
打印格式化字符串。
create_string() {
printf '[%s]\nworld\n' ""
}
我需要使用函数将以下内容保存在文件中。
[hello]
world
我尝试了几种方法,但 none 有效。
#!/bin/bash
create_string() {
str="[]\n"
str="${str}world\n"
echo $str
}
create_string hello >> string.txt
文件是这样的
[hello]\nworld\n
当涉及到多行输出时,我喜欢将 cat
与带有 EOF
作为定界标识符的此处文档一起使用,例如
#!/bin/bash
create_string() {
cat <<EOF
[]
world
EOF
}
create_string hello >> string.txt
创建 string.txt
需要换行符:
$ od -c string.txt
0000000 [ h e l l o ] \n w o r l d \n
0000016
参考文献:
使用printf
打印格式化字符串。
create_string() {
printf '[%s]\nworld\n' ""
}