Skip to content

Instantly share code, notes, and snippets.

@LoganGray
Last active May 23, 2023 16:29
Show Gist options
  • Save LoganGray/d9111c3a882ad5e4c37a6a8576733ef7 to your computer and use it in GitHub Desktop.
Save LoganGray/d9111c3a882ad5e4c37a6a8576733ef7 to your computer and use it in GitHub Desktop.
a relatively simple configuration changer/add-er. If someone out there knows something better - please let me know! ;) Seems like this should already exist
#!/bin/bash
#set-conf bash thing
# for setting a configuration setting in a file defaulting with a : colon assignment
# and adds the setting if it doesn't find it.
#
#setconf <filepath&name> "string" "<setting>"
#i.e. setconf.sh /etc/datadog/datadog.yaml
#first things first!
function replace-line-in-file() {
local file="$1"
local line_num="$2"
local setting="$3"
local settingvalue="$4"
local replacement="$3: $4"
#TODO: determine main assignment character used... maybe test for : occurances per # of lines... vs. occurances of = per lines?
# Escape backslash, forward slash and ampersand for use as a sed replacement.
replacement_escaped=$( echo "$replacement" | sed -e 's/[\/&]/\\&/g' )
sed -i "${line_num}s/.*/$replacement_escaped/" "$file"
}
#TODO: test for existence of all parameters
FILENAME=$1
STRING2CK4=$2
SETTINGVALUE=$3
if [[ -z $FILENAME || -z $STRING2CK4 || -z $SETTINGVALUE ]]; then
echo "all parameters must be passed!"
echo "ex."
echo "setconf.sh <filename & path> <String to search for> <value to set to>"
exit
fi
#TODO: test if permission / access to file exists
echo "Filename: $FILENAME"
echo "STRING2CK4 $STRING2CK4"
echo "SETTINGVALUE: $SETTINGVALUE"
LINE2RPL="$(grep -n -m 1 $STRING2CK4 $FILENAME|sed 's/\([0-9]*\).*/\1/')"
if [ -z "$LINE2RPL" ];
then
echo "line2RPL is blank - item not found - insert it at end of file!"
echo "${STRING2CK4}: ${SETTINGVALUE}" >>$FILENAME
else
echo "line2RPL is set to '$LINE2RPL' - replacing!";
replace-line-in-file $FILENAME $LINE2RPL $STRING2CK4 $SETTINGVALUE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment