How to parse config files with Bash
opensource.com
opensource.com
That's backwards. Dot is the POSIX-standard command; source isn't. So it's more like, in some shells you can use the readable source command instead of the cryptic dot, at the cost of portability.
source does not go without a mention in POSIX. The specification says that if the command name in a command matches one of a certain set of identifiers, the results are unspecified. source is one of those identifiers.
Fun fact: the reason json has as many constraints as it does is because rather than simply parsing json (a trivial thing) the json[2].js implementation used a regex to "validate" it before .. throwing it at eval. That necessarily required huge restrictions on what could be there - you can't use "undefined" in json because it's not actually a keyword, no comments (can't handle those with regex), etc all come from that :-/
Loading json as javascript also led to seemingly odd patterns, like putting an infinite loop before the start of a json payload to prevent injected javascript stealing data.
touch "${APP_CONFIG:=${HOME}/.config/myapp.conf}"
conf_has() { git config -f "${APP_CONFIG}" --get key."$1".val >/dev/null; }
conf_get() { git config -f "${APP_CONFIG}" --get key."$1".val; }
conf_set() { git config -f "${APP_CONFIG}" --replace-all key."$1".val "$2"; }
conf_del() { git config -f "${APP_CONFIG}" --unset-all key."$1".val; }
conf_list() { git config -f "${APP_CONFIG}" --get-regex '^key' | sed -e 's/^key.//' -e 's/\.val /\t/'; }Often you want a source of truth that is true for more than just your bash script.
It should have included a discussion about how sourcing config lets the config author execute code.
I also think you want to export these values. You source your config, maybe setup an environment and then execute a Python script that reads values from the environment.
Other things I was hoping for: a lot of modern tools come with config in json. Is there a reasonable way to read this into bash script?
I thought it was going to be something more like "here's a way to read KEY=VALUE lines into an associative array" (which is pretty easy, and can lead to all sorts of fun discussions/learnings about arrays in bash, subshells, whitespace/$IFS, etc)
It leverages a one-liner awk:
ini_buffer="$(print "%s" "$raw_buffer" | awk '/^\[.*\]$/{obj=$0}/=/{print obj $0}')"
Supporting bash APIs using that one-liner awk:
https://github.com/egberts/bash-ini-file rm() { mv -f $1 $HOME/.Trash; } # move source to ~/.Trash for later removalBut mv does not. Interestingly, it doesn’t appear Apple has added their own cli tool for moving something to the trash in the same way that they provide `open` or `pbcopy` or `pbpaste`
You could execute inline AppleScript to tell the Finder to move the file to the trash, but that’s pretty roundabout