Linux 如何使用带有变量的 Bash 编写多行字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7875540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write multiple line string using Bash with variables?
提问by
How can I write multi-lines in a file called myconfig.conf
using BASH?
如何在myconfig.conf
使用 BASH调用的文件中编写多行?
#!/bin/bash
kernel="2.6.39";
distro="xyz";
echo <<< EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4
line ...
EOL >> /etc/myconfig.conf;
cat /etc/myconfig.conf;
采纳答案by ktf
The syntax (<<<
) and the command used (echo
) is wrong.
语法 ( <<<
) 和使用的命令 ( echo
) 是错误的。
Correct would be:
正确的应该是:
#!/bin/bash
kernel="2.6.39"
distro="xyz"
cat >/etc/myconfig.conf <<EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4 line
...
EOL
cat /etc/myconfig.conf
This construction is referred to as a Here Documentand can be found in the Bash man pages under man --pager='less -p "\s*Here Documents"' bash
.
这种结构被称为Here Document,可以在 Bash 手册页中找到man --pager='less -p "\s*Here Documents"' bash
。
回答by Kent
#!/bin/bash
kernel="2.6.39";
distro="xyz";
cat > /etc/myconfig.conf << EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4
line ...
EOL
this does what you want.
这做你想要的。
回答by William Pursell
The heredoc solutions are certainly the most common way to do this. Other common solutions are:
Heredoc 解决方案当然是最常用的方法。其他常见的解决方案是:
echo 'line 1, '"${kernel}"' line 2, line 3, '"${distro}"' line 4' > /etc/myconfig.conf
and
和
exec 3>&1 # Save current stdout exec > /etc/myconfig.conf echo line 1, ${kernel} echo line 2, echo line 3, ${distro} ... exec 1>&3 # Restore stdout
回答by Tk421
If you do not want variables to be replaced, you need to surround EOL with single quotes.
如果不想替换变量,则需要用单引号将 EOL 括起来。
cat >/tmp/myconfig.conf <<'EOL'
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4 line
...
EOL
Previous example:
上一个例子:
$ cat /tmp/myconfig.conf
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4 line
...
回答by rashok
Below mechanism helps in redirecting multiple lines to file. Keep complete string under "
so that we can redirect values of the variable.
下面的机制有助于将多行重定向到文件。保留完整的字符串,"
以便我们可以重定向变量的值。
#!/bin/bash
kernel="2.6.39"
echo "line 1, ${kernel}
line 2," > a.txt
echo 'line 2, ${kernel}
line 2,' > b.txt
Content of a.txt
is
的内容a.txt
是
line 1, 2.6.39
line 2,
Content of b.txt
is
的内容b.txt
是
line 2, ${kernel}
line 2,