Question

I wrote this test script:

#!/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

When I run it, I get a weird error:

awk: cmd. line:1: BEGIN blocks must have an action part

Was it helpful?

Solution

Put $awk in quotes:

awk -v m="$build_message" -v s="$settings" "$awk" "$file"

OTHER TIPS

The shell is eating your quotes. Typically when I get to problems like this with awk/bash/sed scripting I resort to a temp file.

    ...
    tempfile=$(mktemp)
    echo ${awk} >${tempfile}       
    awk ...  -f ${tempfile} ...
    rm ${tempfile}

Depending on degree of security you want, you might use mktemp to make the directory rather than the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top