Bash Config Files
A config file is a small file that holds settings outside the script. The script reads it at the start and uses its values.
A config file overrides the defaults
The script sets defaults, then writes and reads a config file. The printed values come from the config, not the defaults.
name="guest"
port=8000
printf 'name="backup"\nport=9000\n' > app.conf
[ -f app.conf ] && . ./app.conf
echo "name: $name"
echo "port: $port"A guard keeps a missing config file harmless
No config file exists in this run. The guard skips sourcing, so the defaults print unchanged.
name="guest"
port=8000
if [ -f app.conf ]; then
. ./app.conf
else
echo "no config found"
fi
echo "name: $name"
echo "port: $port"A command-line value beats the config value
The config sets the name, but a value typed on the command line replaces it. The port stays at the config value.
name="guest"
port=8000
printf 'name="backup"\nport=9000\n' > app.conf
[ -f app.conf ] && . ./app.conf
if [ -n "$1" ]; then
name="$1"
fi
echo "name: $name"
echo "port: $port"Example
#!/bin/bash
name="guest"
port=8000
mode="fast"
printf 'name="backup"\nport=9000\n' > app.conf
if [ -f app.conf ]; then
. ./app.conf
fi
if [ -n "$1" ]; then
name="$1"
fi
echo "name: $name"
echo "port: $port"
echo "mode: $mode"Key points
- Default: a value the script uses when nothing else sets it.
- Config file: a file of settings that the script reads in.
- Source: reading a file with . so its settings become variables.
- Override order: defaults first, then config, then command line.
- Missing file guard: a test that skips sourcing when the file is absent.
- Command line wins: a value typed on the command line beats the config.
In this example, the script starts with three defaults. It writes a config file and reads it in, so the name and port change while the mode stays at its default. A value on the command line then replaces the name only. The printed lines show each layer in order: config beats defaults, and the command line beats config.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In what order do settings win, weakest first?