Skip to content

Instantly share code, notes, and snippets.

@leverich
Created September 19, 2015 20:25
Show Gist options
  • Save leverich/d9466ec48f1f08db5865 to your computer and use it in GitHub Desktop.
Save leverich/d9466ec48f1f08db5865 to your computer and use it in GitHub Desktop.
manage a chunk in a conf file
#!/bin/bash
#
# update-conf-file <file to update> [<file to insert> | <directory>]
#
# This script manages the insertion or update of a singleton region of
# a file. You can use it to insert lines into configuration files, and
# cleanly update them later.
#
# If a file to insert is specified, that file will be cat'd into the
# file to update. If a directory is specified, all files that don't
# begin with "." in that directory will be cat'd instead. If no
# additional argument is given, STDIN is inserted into the file to
# update.
set -e
# Random SHA-1 hashes to tag beginning and end of the manage region.
TAG1="a808aeadec93e8e56f625dc607eccc617a8f6e3a"
TAG2="f1d2d2f924e986ac86fdf7b36c94bcdf32beec15"
## TODO
##
## Implement --help.
## Argument to set comment character.
test "$1" || (cat $0; false)
FILE="$1"
test -x "$FILE" || touch "$FILE" # Create it if it doesn't exist.
test -f "$FILE"
test -w "$FILE"
shift
TEMP_INFILE=`tempfile`
TEMP_OUTFILE=`tempfile`
trap "rm $TEMP_INFILE $TEMP_OUTFILE" EXIT
if [ "$1" ]; then
if [ -d "$1" ]; then
cat "$1"/[^.]* > $TEMP_INFILE || true
else
cat "$@" > $TEMP_INFILE
fi
else
cat > $TEMP_INFILE
fi
cat "$FILE" > $TEMP_OUTFILE
(
awk ' { if (!seen) print $0 }
/'$TAG1'/ { seen = 1; }
END { if (!seen) print "# update-conf-file begin '$TAG1'" }' "$FILE"
cat $TEMP_INFILE
awk '/'$TAG2'/ { if (!seen) print $0; seen = 1; }
!/'$TAG2'/ { if (seen) print $0 }
END { if (!seen) print "# update-conf-file end '$TAG2'" }' "$FILE"
) > $TEMP_OUTFILE
cat $TEMP_OUTFILE > "$FILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment