Source once
- source_once.bsh
The source_once.bsh
script provides an easy to use guard that ensures a file will not be sourced (loaded) multiple times. This is analogous to C++’s header guards. This prevents circular source loops, saves time loading files, and produces less debugging output.
To activate the source once feature, the main script need only:
source ${VSI_COMMON_DIR}/linux/source_once.bsh
Every file that you want to be able to use this feature should have the following header
#!/usr/bin/env bash
if [[ ${-} != *i* ]]; then
source_once &> /dev/null && return 0
fi
This header is written such that source_once
is an optional component. If source_once.bsh
hasn’t been sourced, this feature will do nothing, and continue.
In interactive mode, source_once
is disabled and files are always source. This gives a more reliable experience to users in case files are updated, and prevents command_not_found_handle from triggering, which can be very costly.
Even though source_once.bsh
is not dash
compatible, a modified header can at least make the line that attempts to call source_once
be dash
compatible:
source_once > /dev/null 2>&1 && return 0
- source_once
- Output:
Returns
1
if this is the first time, else0
for already called- Internal Use:
_VSI_ALREADY_SOURCED
- State array used onbash
4 or newer_VSI_ALREADY_SOURCED_*
- State variables used forbash
3.2
Checks to see if the calling file has been used to call source_once
. The intended use is to check if a file has been sourced already or not (by using BASH_SOURCE
).