Tricks & personal rules. Work in progress.
- Setup
- Includes, set statements, etc.
- Constants
- Functions
- Define all functions. The last one should be a
main
function that wraps up other functions. - Main
- Executable code.
Since my utilities are all in the same directory, I just need to find the current script’s directory to find any dependency:
# Find the current script's directory
script_dir="$(dirname "$(readlink -f "$0")")"
# Load a dependency
source "${script_dir}/org-create-lifelog.sh"
This works even when the parent script is run through a symlink (all
my scripts are usually symlinked in ~/bin
.
When sourcing a script to include its functions, we don’t want to
execute the main
function. It can be wrapped in a condition like
this:
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
Optional parameters can be implemented using the default-value syntax:
main() {
local target_dir=${1:-${default_target_dir}}
local week_string=${2:-${default_week_string}}
new_lifelog "${target_dir}" "${week_string}"
}
main "$@"
Doing so should probably be main
’s job.
See this SO answer.