Skip to content

Instantly share code, notes, and snippets.

@mkaito
Created February 22, 2012 15:48
Show Gist options
  • Save mkaito/1885631 to your computer and use it in GitHub Desktop.
Save mkaito/1885631 to your computer and use it in GitHub Desktop.
rc-file reading in a shell script
#!/usr/bin/env zsh
# An example script that reads a colon separated rc file, given on argv
# Line format expected:
# option: value
# Mind the colon and space separating option name from the value.
# Adjust the parameter expansion as needed if you change the line format.
# - read <var> will read a line at a time.
# - Piping the file name into the while block reads the file into the read call.
# - typeset -A <var> explicitly marks a hash for ZSH.
# declare -A <var> is the same for bash.
# - Fancypants parameter expansion gives us opts[option]=value.
# - Quoting the value allows is to be any valid string, which generally means
# that the value will be anything between the colon and the next newline character.
if [[ -f $1 ]]; then
typeset -A opts
while read l; do
opts[${l%%:*}]="${l##*: }"
done < $1
fi
echo "Number of found options: ${#opts[*]}"
for k in ${(k)opts}; do
echo "$k => ${opts[$k]}"
done
@mkaito
Copy link
Author

mkaito commented Feb 22, 2012

Of course, there are other ways to read options from a file. For one, you could simply have it be a regular shell script defining variables, and source it. On the upside, anything valid in a shell script can go there, so you can work some magic on your configuration. On the downside, your config file is a shell script which will be executed upon sourcing, which is good and bad, depending on how prone you are to accidentally writing things like rm -rf ~ in your files.

Certain applications may require sectioned config files, like the traditional ini-file syntax, where sections are separated with [Header] lines. This kind of configuration will require some sed/awk magic, and storing the options will also become a lot more complicated, since shells only support one-dimension arrays. At the very least, you'll be dealing with a section list in one array, and one array per section to store it's options.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment