如何将template.txt包含为脚本的here-doc



我有一个模板文件(template.txt):

Hello, $x
Hello, $y

我有一个脚本文件(script.sh):

#!/bin/bash
$x=linux
$y=unix
# I want to include template.txt as a here-doc

如何将template.txt包含为script.shhere-doc
因此,当我运行script.sh时,输出应该是:

Hello, linux
Hello, unix

编辑:

我认为replace对我的工作来说是一个很好的命令:

$ cat template.txt | replace '$x' linux '$y' unix

一个更复杂的工具:

$ cheetah compile template.tmpl
$ x=linux y=unix python template.py --env

下面的bash函数将任意文件求值为here文档,允许bash用作迷你模板语言。它不需要任何临时文件。

#!/bin/bash
template() {
  file=$1
  shift
  eval "`printf 'local %sn' $@`
cat <<EOF
`cat $file`
EOF"
}

变量将从环境中展开,或者可以直接传递,例如模板文件

Hello $x, $y, $z

和摘录

y=42
for i in 1 2; do
  template template.txt x=$i z=end
done

输出将是

Hello 1, 42, end
Hello 2, 42, end

请注意,模板文件中的任意代码也将被执行,因此请确保您信任编写它的人。

我在一个项目中使用了这个函数。它从模板构建一个实际的here文档,然后使用.:在当前shell中执行它

# usage: apply_template /path/to/template.txt
apply_template () {
        (
        trap 'rm -f $tempfile' EXIT
        tempfile=$(mktemp $(pwd)/templateXXXXXX)
        echo 'cat <<END_TEMPLATE' > $tempfile
        cat $1 >> $tempfile
        echo END_TEMPLATE >> $tempfile
        . $tempfile
        )
}
#!/bin/bash
x=linux
y=unix
cat << EOF
Hello, $x
Hello, $y
EOF

这可能对你有用(GNU sed):

cat <<! >template.txt
Hello, $x
Hello, $y
!
cat <<! >replace
export "$@"
sed -e '1icat <<EOT' -e '$aEOT' | sed ':a;$!{N;ba};e'
!
cat template.txt | replace x='Fred Flintstone' y='Barney Rubble'
Hello, Fred Flintstone
Hello, Barney Rubble

这是我提出的解决方案:

eval $'cat <<02n'"$(<ifile)"$'n02' > ofile

02可以替换为ifile中未出现的任何字符或字符串。删除输入文件中出现的任何分隔字符:

eval $'cat <<02n'"$(tr -d '02' < ifile)"$'n02' > ofile

此解决方案似乎解决了大多数问题,但特别容易受到通过$(command)指令在模板文件中注入命令的攻击。

最新更新