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

当前回答

我通常把模板放在文件中并使用这个模板引擎:

### <template-file> [ARG=VALUE..]
## Variables are replaced only within "{{" and "}}" notation.
## Example:
##         $0 path-to-tmpl REF=master pass=xx
##         # The template may look like so:
##         #    $pass = ["user", "{{ $pass }}"];
##         # Resulting in:
##         #    $pass = ["user", "xxx"];
##~
template() {
    tmpl=$1
    shift

    for i in $@; do
        declare $i;
    done

    eval "echo \"$(sed -e 's/"/\\"/g' -e 's/\$/\\$/g' -e 's/{{\s*\\\(\$\w*\)\s*}}/\1/g' $tmpl)\""
}

其他回答

如果不希望替换变量,则需要用单引号将EOL括起来。

cat >/tmp/myconfig.conf <<'EOL'
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 
EOL

前一个例子:

$ cat /tmp/myconfig.conf 
line 1, ${kernel}
line 2, 
line 3, ${distro}
line 4 line
... 

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

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" ...

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

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

我使用Mac OS和写多行在SH脚本下面的代码为我工作

#! /bin/bash
FILE_NAME="SomeRandomFile"

touch $FILE_NAME

echo """I wrote all
the  
stuff
here.
And to access a variable we can use
$FILE_NAME  

""" >> $FILE_NAME

cat $FILE_NAME

请不要忘记根据需要为脚本文件分配chmod。 我用过

chmod u+x myScriptFile.sh

语法(<<<)和使用的命令(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下找到。