Script Libraries and Sourcing
Script Libraries and Sourcing
Modular scripts reuse libraries using source or .. Prevent multiple inclusions using header guards:
# lib/logger.sh
[[ -n "${_LIB_LOGGER_SH:-}" ]] && return 0
readonly _LIB_LOGGER_SH=1
log_info() {
printf '[%s] [INFO] %s\n' "$(date +'%Y-%m-%dT%H:%M:%S%z')" "$*" >&2
}Locate libraries reliably relative to the executing script:
# Locate directory containing this script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/../lib/logger.sh"