Skip to content

Latest commit

 

History

History
96 lines (71 loc) · 2.06 KB

bash_notes.org

File metadata and controls

96 lines (71 loc) · 2.06 KB

Bash notes

Tricks & personal rules. Work in progress.

Style

File structure

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.

Tricks

Loading dependencies

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.

Do not execute main when sourcing

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

Use optional parameters

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.

Process options

See this SO answer.

Resources