I have some shell functions that I use for personal development. I would like to create config files on a per-project basis so that the functions read the config file and use values from the config file, if present.
This is a very basic example:
path/to/project/functions.sh (works)
#!/usr/bin/env bash
PROJECT_KEY="abc"
function project_name() {
if [ -d ".config" ]; then
. .config
fi
echo $PROJECT_KEY # => "def"
}
path/to/project/.config
PROJECT_KEY="def"
The above works, but I have dozens of these utility/helper functions, and I wanted to load the config via another function if it exists.
path/to/project/functions.sh (does not work)
#!/usr/bin/env bash
function load_config() {
if [ -f ".config" ]; then
. ".config"
elif [ -f "~/.config" ]; then
. "~/.config"
fi
}
function project_name() {
load_config
echo $PROJECT_KEY # => "abc"
}
I believe that the load_config()
function is sourcing the config file into the load_config()
function, and then when that function returns/exits, the sourced variables are gone because they are scoped to the individual function call, ie, the load_config()
function.
I understand my current approach isn’t working, but I don’t know how to avoid executing source .config
all over the place. I want to put it in a single function that is called.
How do I cleanly read config files in my functions without a ton of duplicate code?