Using Configuration Files in a Script

Problem

You want to use one or more external configuration files for one or more scripts.

Solution

You could write a lot of code to parse some special configuration file format. Do yourself a favor and don’t do that. Just make the config file a shell script and use the solution in Reusing Code with Includes and Sourcing.

Discussion

This is just a specific application of sourcing a file. However, it’s worth noting that you may need to give a little thought as to how you can reduce all of your configuration needs to bash-legal syntax. In particular, you can make use of Boolean flags, and optional variables (see Chapter 5 and Getting Input from Another Machine).

# In config file
VERBOSE=0                # '' for off, 1 for on
SSH_USER='jbagadonutz@'  # Note trailing @, set to '' to use the current user
# In script
[ "$VERBOSE" ] || echo "Verbose msg from $) goes to STDERR" >&2
[...]
ssh$SSH_USER$REMOTE_HOST [...]

Of course, depending on the user to get the configuration file correct can be chancy, so instead of requiring the user to read the comment and add the trailing @, we could do it in the script:

# If $SSH_USER is set and doesn't have a trailing @ add it:
[ -n "$SSH_USER" -a "$SSH_USER" = "${SSH_USER%@}" ] && SSH_USER="$SSH_USER@"

Or just use:

ssh ${SSH_USER:+${SSH_USER}@}${REMOTE_HOST} [...]

to make that same substitution right in place. The bash variable operator :+ will do the following: if $SSH_USER has a value, it will return the value to the right of the :+ (in ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.