06 March 2015

Sometimes, we need to update configure files using a shell script (or whatever). Simple it might seem, there some triky things:

  1. We need to make sure that running the script multiple times is OK. For exmple, the script should not append a line to a configure file again and again.
  2. We need to ensure we can remove our changes from a configure file later. This cannot always achieved by saving a copy of the original configure file since other applications may also update the configure file and we must not overwrite those modifications when we do "restore".

My solution is basically to "mark" our changes in place so that we can easily spot and undo the changes later on.

Supppose I have a file with the following content:

orginal line 1
...
orginal line m
...
orginal line n

Now, after deleting line m and adding some new lines with my Technique, this file will be some like this (Note that I am supposign '#' starts a comment.):

orginal line 1
...
#DEL_LGFANG orginal line m
...
orginal line n
#BEGIN_LGFANG
New lines are in between
Other applications shall never modify this block
#END_LGFANG

To restore the file, all that we need to do are:

  1. Delete line between #BEGIN_LGFANG and #END_LGFANG.
  2. Remove any leading #DEL_LGFANG

Below are bash functions which facilitate the work as well as examples of usage.

function add {
    local filename=$1
    local lines=$2
    cat >> $filename <<EOF
#BEGIN_LGFANG
$lines
#END_LGFANG
EOF
}

function del {
    local filename=$1
    local target_line=$2
    sed -i "/${target_line}/s/\(#DEL_LGFANG \)*\(.*\)$/#DEL_LGFANG \2/" $filename
}

function restore {
    # 1. delete added
    # 2. restore deleted (uncomment commented)

    local filename=$1
    sed -i -e '/BEGIN_LGFANG/,/END_LGFANG/d' \
        -e 's/^.*DEL_LGFANG *//' $filename
}

# Examples
lines='line1
line2'

add test.conf "$lines"
del test.conf todel
restore test.conf


blog comments powered by Disqus