我写了这个测试脚本:
#!/bin/bash
build_message='build'
# On first run, the supplied settings block is appended to the supplied config
# file surrounded by comments ("# build START" and "# build END").
# On subsequent runs, the lines in between the two comments will be replaced
# by the provided settings block.
config-insert () {
settings="$1"
file="$2"
awk='BEGIN { p = 1; o = 1; }
$0 ~ "^# " m " START" { p = 0; if (o) output(); o = 0; }
$0 ~ "^# " m " END"{ p = 1; next }
END { if (o) output(o); }
{ if (p) print $0; }
function output() { print "# " m " START\n" s "\n# " m " END"; }'
awk -v m="$build_message" -v s="$settings" $awk $file > $file
}
config-insert "setting block" testfile
当我运行它时,我得到一个奇怪的错误:
awk:cmd。 line:1:BEGIN块必须有一个动作部分
答案 0 :(得分:2)
将$ awk放在引号中:
awk -v m="$build_message" -v s="$settings" "$awk" "$file"
答案 1 :(得分:1)
贝壳正在吃你的报价。通常当我使用awk / bash / sed脚本来解决这样的问题时,我会使用临时文件。
...
tempfile=$(mktemp)
echo ${awk} >${tempfile}
awk ... -f ${tempfile} ...
rm ${tempfile}
根据您想要的安全程度,您可以使用mktemp来创建目录而不是文件。