Vla*_*sny 118 bash templates templating
我正在编写一个脚本来自动为我自己的web服务器创建Apache和PHP的配置文件.我不想使用像CPanel或ISPConfig这样的任何GUI.
我有一些Apache和PHP配置文件的模板.Bash脚本需要读取模板,进行变量替换并将解析后的模板输出到某个文件夹中.最好的方法是什么?我可以想到几种方法.哪一个是最好的还是有更好的方法可以做到这一点?我想在纯Bash中做到这一点(例如在PHP中很容易)
template.txt:
the number is ${i}
the word is ${word}
Run Code Online (Sandbox Code Playgroud)
script.sh:
#!/bin/sh
#set variables
i=1
word="dog"
#read in template one line at the time, and replace variables
#(more natural (and efficient) way, thanks to Jonathan Leffler)
while read line
do
eval echo "$line"
done < "./template.txt"
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如何在此处将输出重定向到外部文件?如果变量包含引号,我是否需要逃避某些事情?
2)使用cat&sed替换每个变量的值:
给出template.txt:
The number is ${i}
The word is ${word}
Run Code Online (Sandbox Code Playgroud)
命令:
cat template.txt | sed -e "s/\${i}/1/" | sed -e "s/\${word}/dog/"
Run Code Online (Sandbox Code Playgroud)
对我来说似乎不好,因为需要逃避许多不同的符号,并且对于许多变量,这条线太长了.
你能想到其他一些优雅而安全的解决方案吗?
小智 121
尝试 envsubst
FOO=foo
BAR=bar
export FOO BAR
envsubst <<EOF
FOO is $FOO
BAR is $BAR
EOF
Run Code Online (Sandbox Code Playgroud)
ZyX*_*ZyX 58
你可以用这个:
perl -p -i -e 's/\$\{([^}]+)\}/defined $ENV{$1} ? $ENV{$1} : $&/eg' < template.txt
Run Code Online (Sandbox Code Playgroud)
${...}用相应的环境变量替换所有字符串(不要忘记在运行此脚本之前导出它们).
对于纯bash,这应该有效(假设变量不包含$ {...}字符串):
#!/bin/bash
while read -r line ; do
while [[ "$line" =~ (\$\{[a-zA-Z_][a-zA-Z_0-9]*\}) ]] ; do
LHS=${BASH_REMATCH[1]}
RHS="$(eval echo "\"$LHS\"")"
line=${line//$LHS/$RHS}
done
echo "$line"
done
Run Code Online (Sandbox Code Playgroud)
.如果RHS引用一些引用自身的变量,则不会挂起的解决方案:
#!/bin/bash
line="$(cat; echo -n a)"
end_offset=${#line}
while [[ "${line:0:$end_offset}" =~ (.*)(\$\{([a-zA-Z_][a-zA-Z_0-9]*)\})(.*) ]] ; do
PRE="${BASH_REMATCH[1]}"
POST="${BASH_REMATCH[4]}${line:$end_offset:${#line}}"
VARNAME="${BASH_REMATCH[3]}"
eval 'VARVAL="$'$VARNAME'"'
line="$PRE$VARVAL$POST"
end_offset=${#PRE}
done
echo -n "${line:0:-1}"
警告:我不知道如何在bash中正确处理NUL的输入或保留尾随换行的数量.最后一个变体是因为它是"爱"二进制输入:
read 将解释反斜杠.read -r 不会解释反斜杠,但如果不以换行符结尾,仍然会删除最后一行."$(…)"将去除尽可能多的尾随换行符则不存在,所以我最终…与; echo -n a和使用echo -n "${line:0:-1}":此下降的最后一个字符(这是a),并作为有在输入(包括无)保留尽可能多的后换行.Dan*_*ite 39
envsubst对我来说很新鲜.太棒了.
对于记录,使用heredoc是模拟conf文件的好方法.
STATUS_URI="/hows-it-goin"; MONITOR_IP="10.10.2.15";
cat >/etc/apache2/conf.d/mod_status.conf <<EOF
<Location ${STATUS_URI}>
SetHandler server-status
Order deny,allow
Deny from all
Allow from ${MONITOR_IP}
</Location>
EOF
Run Code Online (Sandbox Code Playgroud)
Hai*_* Vu 31
我同意使用sed:它是搜索/替换的最佳工具.这是我的方法:
$ cat template.txt
the number is ${i}
the dog's name is ${name}
$ cat replace.sed
s/${i}/5/
s/${name}/Fido/
$ sed -f replace.sed template.txt > out.txt
$ cat out.txt
the number is 5
the dog's name is Fido
Run Code Online (Sandbox Code Playgroud)
mog*_*sie 23
我认为eval的效果非常好.它处理带有换行符,空格和各种bash内容的模板.如果您当然可以完全控制模板本身:
$ cat template.txt
variable1 = ${variable1}
variable2 = $variable2
my-ip = \"$(curl -s ifconfig.me)\"
$ echo $variable1
AAA
$ echo $variable2
BBB
$ eval "echo \"$(<template.txt)\"" 2> /dev/null
variable1 = AAA
variable2 = BBB
my-ip = "11.22.33.44"
Run Code Online (Sandbox Code Playgroud)
当然,应该谨慎使用此方法,因为eval可以执行任意代码.以root身份运行这几乎是不可能的.模板中的引号需要转义,否则它们将被吃掉eval.
如果您愿意cat,也可以使用此处的文档echo
$ eval "cat <<< \"$(<template.txt)\"" 2> /dev/null
Run Code Online (Sandbox Code Playgroud)
@plockc提出了一个避免bash引用转义问题的解决方案:
$ eval "cat <<EOF
$(<template.txt)
EOF
" 2> /dev/null
Run Code Online (Sandbox Code Playgroud)
编辑:删除部分关于使用sudo以root身份运行它...
编辑:添加了关于如何转义报价的评论,添加了plockc的混合解决方案!
plo*_*ckc 19
我有像mogsie这样的bash解决方案但是使用heredoc而不是herestring来避免转义双引号
eval "cat <<EOF
$(<template.txt)
EOF
" 2> /dev/null
Run Code Online (Sandbox Code Playgroud)
CKK*_*CKK 16
我需要在配置文件中保留双引号,以便使用sed双重转义双引号有助于:
render_template() {
eval "echo \"$(sed 's/\"/\\\\"/g' $1)\""
}
Run Code Online (Sandbox Code Playgroud)
我想不到保留尾随的新行,但保留了两行之间的空行.
虽然这是一个老话题,IMO我在这里找到了更优雅的解决方案:http://pempek.net/articles/2013/07/08/bash-sh-as-template-engine/
#!/bin/sh
# render a template configuration file
# expand variables + preserve formatting
render_template() {
eval "echo \"$(cat $1)\""
}
user="Gregory"
render_template /path/to/template.txt > path/to/configuration_file
Run Code Online (Sandbox Code Playgroud)
所有学分都归GrégoryPakosz所有.
接受答案的更长但更强大的版本:
perl -pe 's;(\\*)(\$([a-zA-Z_][a-zA-Z_0-9]*)|\$\{([a-zA-Z_][a-zA-Z_0-9]*)\})?;substr($1,0,int(length($1)/2)).($2&&length($1)%2?$2:$ENV{$3||$4});eg' template.txt
Run Code Online (Sandbox Code Playgroud)
这扩大所有实例$VAR 或 ${VAR}他们的环境值(或者,如果他们是不确定的,空字符串).
它正确地逃避反斜杠,并接受反斜杠转义$来禁止替换(与envsubst不同,事实证明,它不会这样做).
因此,如果您的环境是:
FOO=bar
BAZ=kenny
TARGET=backslashes
NOPE=engi
Run Code Online (Sandbox Code Playgroud)
你的模板是:
Two ${TARGET} walk into a \\$FOO. \\\\
\\\$FOO says, "Delete C:\\Windows\\System32, it's a virus."
$BAZ replies, "\${NOPE}s."
Run Code Online (Sandbox Code Playgroud)
结果将是:
Two backslashes walk into a \bar. \\
\$FOO says, "Delete C:\Windows\System32, it's a virus."
kenny replies, "${NOPE}s."
Run Code Online (Sandbox Code Playgroud)
如果你只想在$之前转义反斜杠(你可以在模板中写"C:\ Windows\System32"不变),使用这个稍微修改过的版本:
perl -pe 's;(\\*)(\$([a-zA-Z_][a-zA-Z_0-9]*)|\$\{([a-zA-Z_][a-zA-Z_0-9]*)\});substr($1,0,int(length($1)/2)).(length($1)%2?$2:$ENV{$3||$4});eg' template.txt
Run Code Online (Sandbox Code Playgroud)
我这样做了,效率可能不高,但更容易阅读/维护.
TEMPLATE='/path/to/template.file'
OUTPUT='/path/to/output.file'
while read LINE; do
echo $LINE |
sed 's/VARONE/NEWVALA/g' |
sed 's/VARTWO/NEWVALB/g' |
sed 's/VARTHR/NEWVALC/g' >> $OUTPUT
done < $TEMPLATE
Run Code Online (Sandbox Code Playgroud)
使用envsubst而不是重新发明轮子 几乎可以在任何场景中使用,例如从docker容器中的环境变量构建配置文件.
如果在mac上确保你有自制软件,那么从gettext链接它:
brew install gettext
brew link --force gettext
Run Code Online (Sandbox Code Playgroud)
./template.cfg
# We put env variables into placeholders here
this_variable_1 = ${SOME_VARIABLE_1}
this_variable_2 = ${SOME_VARIABLE_2}
Run Code Online (Sandbox Code Playgroud)
./.env:
SOME_VARIABLE_1=value_1
SOME_VARIABLE_2=value_2
Run Code Online (Sandbox Code Playgroud)
./configure.sh
#!/bin/bash
cat template.cfg | envsubst > whatever.cfg
Run Code Online (Sandbox Code Playgroud)
现在只需使用它:
# make script executable
chmod +x ./configure.sh
# source your variables
. .env
# export your variables
# In practice you may not have to manually export variables
# if your solution depends on tools that utilise .env file
# automatically like pipenv etc.
export SOME_VARIABLE_1 SOME_VARIABLE_2
# Create your config file
./configure.sh
Run Code Online (Sandbox Code Playgroud)
这是另一个纯 bash 解决方案:
$ cat code
#!/bin/bash
LISTING=$( ls )
cat_template() {
echo "cat << EOT"
cat "$1"
echo EOT
}
cat_template template | LISTING="$LISTING" bash
Run Code Online (Sandbox Code Playgroud)
$ cat template (带有尾随换行符和双引号)
<html>
<head>
</head>
<body>
<p>"directory listing"
<pre>
$( echo "$LISTING" | sed 's/^/ /' )
<pre>
</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
输出
<html>
<head>
</head>
<body>
<p>"directory listing"
<pre>
code
template
<pre>
</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这是另一个解决方案:使用模板文件的所有变量和内容生成一个 bash 脚本,该脚本如下所示:
word=dog
i=1
cat << EOF
the number is ${i}
the word is ${word}
EOF
Run Code Online (Sandbox Code Playgroud)
如果我们将此脚本输入 bash,它将产生所需的输出:
the number is 1
the word is dog
Run Code Online (Sandbox Code Playgroud)
以下是生成该脚本并将该脚本输入 bash 的方法:
(
# Variables
echo word=dog
echo i=1
# add the template
echo "cat << EOF"
cat template.txt
echo EOF
) | bash
Run Code Online (Sandbox Code Playgroud)
cat使用 HEREDOC生成命令如果要将此输出重定向到文件中,请将最后一行替换为:
) | bash > output.txt
Run Code Online (Sandbox Code Playgroud)使用纯bash从ZyX获得答案但是使用新样式正则表达式匹配和间接参数替换它变为:
#!/bin/bash
regex='\$\{([a-zA-Z_][a-zA-Z_0-9]*)\}'
while read line; do
while [[ "$line" =~ $regex ]]; do
param="${BASH_REMATCH[1]}"
line=${line//${BASH_REMATCH[0]}/${!param}}
done
echo $line
done
Run Code Online (Sandbox Code Playgroud)
如果使用Perl是一种选择,并且您满足于仅基于环境变量(而不是所有shell变量)进行扩展,请考虑Stuart P. Bentley 的可靠答案。
这个答案旨在提供一个只使用bash 的解决方案,尽管使用了eval- 应该可以安全使用。
该目标是:
${name}和$name变量引用。$(...)和遗留语法`...`)$((...))和遗留语法$[...])。\( \${name})选择性抑制变量扩展。"和\实例。功能expandVars():
expandVars() {
local txtToEval=$* txtToEvalEscaped
# If no arguments were passed, process stdin input.
(( $# == 0 )) && IFS= read -r -d '' txtToEval
# Disable command substitutions and arithmetic expansions to prevent execution
# of arbitrary commands.
# Note that selectively allowing $((...)) or $[...] to enable arithmetic
# expressions is NOT safe, because command substitutions could be embedded in them.
# If you fully trust or control the input, you can remove the `tr` calls below
IFS= read -r -d '' txtToEvalEscaped < <(printf %s "$txtToEval" | tr '`([' '\1\2\3')
# Pass the string to `eval`, escaping embedded double quotes first.
# `printf %s` ensures that the string is printed without interpretation
# (after processing by by bash).
# The `tr` command reconverts the previously escaped chars. back to their
# literal original.
eval printf %s "\"${txtToEvalEscaped//\"/\\\"}\"" | tr '\1\2\3' '`(['
}
Run Code Online (Sandbox Code Playgroud)
例子:
$ expandVars '\$HOME="$HOME"; `date` and $(ls)'
$HOME="/home/jdoe"; `date` and $(ls) # only $HOME was expanded
$ printf '\$SHELL=${SHELL}, but "$(( 1 \ 2 ))" will not expand' | expandVars
$SHELL=/bin/bash, but "$(( 1 \ 2 ))" will not expand # only ${SHELL} was expanded
Run Code Online (Sandbox Code Playgroud)
${HOME:0:10},只要它们不包含嵌入式命令或算术替换,例如${HOME:0:$(echo 10)}
$(和`实例都被盲目地转义了)。${HOME(缺少关闭})BREAK 函数。\$name 防止扩张。\没有跟在后面的$被保留原样。\实例,则必须将它们加倍;例如:
\\-> \- 和刚才一样\\\\\ -> \\0x1, 0x2, 0x3.eval.如果您正在寻找仅支持扩展的更具限制性的解决方案${name}- 即,使用强制大括号,忽略$name引用 - 请参阅我的这个答案。
这是已接受答案中仅 bash 的eval免费解决方案的改进版本:
改进之处是:
${name}和$name变量引用。\转义不应扩展的变量引用。eval上面基于 - 的解决方案不同,
expandVars() {
local txtToEval=$* txtToEvalEscaped
# If no arguments were passed, process stdin input.
(( $# == 0 )) && IFS= read -r -d '' txtToEval
# Disable command substitutions and arithmetic expansions to prevent execution
# of arbitrary commands.
# Note that selectively allowing $((...)) or $[...] to enable arithmetic
# expressions is NOT safe, because command substitutions could be embedded in them.
# If you fully trust or control the input, you can remove the `tr` calls below
IFS= read -r -d '' txtToEvalEscaped < <(printf %s "$txtToEval" | tr '`([' '\1\2\3')
# Pass the string to `eval`, escaping embedded double quotes first.
# `printf %s` ensures that the string is printed without interpretation
# (after processing by by bash).
# The `tr` command reconverts the previously escaped chars. back to their
# literal original.
eval printf %s "\"${txtToEvalEscaped//\"/\\\"}\"" | tr '\1\2\3' '`(['
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95025 次 |
| 最近记录: |