如何使用BASH在名为myconfig.conf
的文件中编写多行内容?
#!/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;
语法(<<<
)和所使用的命令(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";
distro="xyz";
cat > /etc/myconfig.conf << EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4
line ...
EOL
这将实现你想要的功能。
如果您不希望替换变量,您需要在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
...
'EOL'
。 - undefinedheredoc方案无疑是最常用的方法。其他常见的解决方案包括:
echo 'line 1, '"${kernel}"'
line 2,
line 3, '"${distro}"'
line 4' > /etc/myconfig.conf
以及
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
和
printf "%s\n" "line1, ${kernel}" "line2," "line3, $distro" ...
我使用的是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 u+x myScriptFile.sh
"
下面,这样我们就可以重定向变量的值。#!/bin/bash
kernel="2.6.39"
echo "line 1, ${kernel}
line 2," > a.txt
echo 'line 2, ${kernel}
line 2,' > b.txt
a.txt
的内容是:
line 1, 2.6.39
line 2,
b.txt
的内容是:
line 2, ${kernel}
line 2,
{
...
printf "Suites: $SUITES"
printf "Components: $COMPONENTS"
printf "Signed-By: $SIGNATURE"
[ ! -z "$ARCH_STRING" ] && printf "$ARCH_STRING"
[ ! -z "$LANG_STRING" ] && printf "$LANG_STRING"
[ ! -z "$TARGET_STRING" ] && printf "$TARGET_STRING"
...
} > /tmp/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)\""
}
我认为还有一种更简单的方法,但适用于少量代码行。
touch myfile.txt
echo "line1">>myfile.txt
echo "line2">>myfile.txt
echo "line3">>myfile.txt
echo "line4">>myfile.txt
EOF
前面没有空格,否则它将无法被识别,你会遇到一个 意外的文件结尾 错误。 - nwinkler