我如何写多行文件称为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;

当前回答

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

这就是你想要的。

其他回答

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

这就是你想要的。

另一种更简单的方法,但绝对适用于少量的行数

touch myfile.txt
echo "line1">>myfile.txt
echo "line2">>myfile.txt
echo "line3">>myfile.txt
echo "line4">>myfile.txt

这里的解决方案当然是最常见的方法。其他常见的解决方案有:

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

and

printf "%s\n" "line1, ${kernel}" "line2," "line3, $distro" ...

语法(<<<)和使用的命令(echo)错误。

正确的做法是:

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

这个结构被称为Here Document,可以在Bash手册页的man -pager='less -p "\s*Here Documents"' Bash下找到。

下面的机制有助于重定向多行文件。在"下面保留完整的字符串,这样我们就可以重定向变量的值。

#!/bin/bash
kernel="2.6.39"
echo "line 1, ${kernel}
line 2," > a.txt
echo 'line 2, ${kernel}
line 2,' > b.txt

.txt的内容为

line 1, 2.6.39
line 2,

b.txt的内容为

line 2, ${kernel}
line 2,