Scripting Linux Configuration Files

by Thomas Urban

Linux strongly depends on a huge number of configuration files. Most of them use a flat key-value pair syntax with providing one named option per line starting with option's name followed by its value. If you ever need to control such files from a shell script you might use some code like this:

writeConfig() {
	FILE="${1}"
	KEY="${2}"
	VALUE="${3}"

	[ $# -lt 3 ] && REMOVE=1 || REMOVE=0
	SEP="${SEP:-=}"
	SUDO="${SUDO:+sudo -E}"
	EXPORT="${EXPORT:+export }"

	QKEY="${KEY//\//\\/}"

	if [ "(" "$VALUE" != "${VALUE/[ 	\"]}" -o -n "${QUOTE}" ")" -a -z "${RAW}" ]; then
		# got value containing whitespace or quotes -> wrap with double quotes
		VALUE="\"${VALUE//\"/\\\"}\""
	fi

	$SUDO touch "$FILE"
	result=$(VALUE="$VALUE" REMOVE="$REMOVE" $SUDO perl -i.bak -nle "BEGIN{\$found=0;}END{if(!\$found){print\"notfound\"}}if(/^((\s*)(export\s*)?($QKEY\s*$SEP\s*))/ and !\$found){print(\$2.(\$ENV{'EXPORT'}?(\$3?\$3:\"\$ENV{'EXPORT'}\"):\"\").\"\$4\$ENV{'VALUE'}\") if(!\$ENV{'REMOVE'});\$found=1;}else{print \$_;}" "$FILE")
	[ $? -eq 0 ] && $SUDO rm "$FILE.bak" &>/dev/null
	[ "$result" == "notfound" -a "$REMOVE" == "0" ] && $SUDO /bin/bash -c "cat >>\"$FILE\"" <<<"$EXPORT$KEY$SEP$VALUE" || [ -z "" ]
}

This snippet relies on bash syntax and is defining some function writeConfig to locally use in your script, e.g.

#!/bin/bash
writeConfig() {
...
}

writeConfig "$@"

It tries to rely on tools commonly available in Linux - bash, perl and optionally sudo. It's capable of adding, removing and adjusting configuration options:

writeConfig ~/some/config.file.txt optName "my option value"
writeConfig ~/some/config.file.txt optName "my adjusted option value"
writeConfig ~/some/config.file.txt optName

It is supporting different kinds of separators separating keys from values:

SEP=" " writeConfig ~/some/config.file.txt optName "my option value"
SEP=":fancy:" writeConfig ~/some/config.file.txt optName "my option value"

It's even supporting sudo to control configuration files requiring elevated privileges:

SUDO=1 writeConfig /etc/some/config.file.txt optName "my option value"

The snippet implicitly detects white space wrapping value in quotes automatically:

writeConfig /etc/some/config.file.txt optName unquotedOptionValue
writeConfig /etc/some/config.file.txt optName 'quoted Option Value'

This quoting may be enforced:

QUOTE=1 writeConfig /etc/some/config.file.txt optName quotedOptionValue

or suppressed:

RAW=1 writeConfig /etc/some/config.file.txt optName 'unquoted Option Value'

Of course it is possible to combine all switches described before:

SUDO=1 SEP=" " QUOTE=1 writeConfig /etc/some/config.file.txt optName on

All examples require to define that function first. You might put it into some script as demonstrated above if you want to have a separate command providing all this.

Go back