How to set source_once in bash?

What a good way to search only once in bash.

Does bash save paths to files that were received, or do I need to make all calls to source / . , through a shell that will store these paths?

Is there a standard mechanism that will find what resolves the original argument? which does not seem to work if the file is not executable.

+6
source share
2 answers

In each of your files that you can use, add instructions. Suppose the /etc/interface file is one of the files you want to use only once, then format this file as follows:

 if [ ! "$ETC_INTERFACE" ] then # statements that you # want to source... fi export ETC_INTERFACE=Yes 

This ensures that statements in /etc/interface are executed only once. If the script tries to run it again, it will see that ETC_INTERFACE set and skips the body of the file.

Alternative approach

Suppose you do not want to modify the files that should be received, but it is normal to modify the scripts that invoke them. In this case, send them as follows:

 [ ! "$ETC_INTERFACE" ] && source /etc/interface && export ETC_INTERFACE=Yes 
+6
source

Below I decided:

 #Store source-in paths in a global hash declare -A SOURCES #Resolve paths manually path_resolve(){ #Absolute paths resolve to themselves [[ "$1" =~ ^/ ]] && { echo "$1"; return 0; } #Otherwise resolve against $PWD and then $PATH items local search_path=$PWD:$PATH local IFS=: for p in $search_path; do [[ -r "$p/$1" ]] && { echo "$p/$1"; return 0; } done return 1 } #Helper function warn(){ echo >&2 " $@ "; } #AKA source_once AKA include_once require(){ local path=$(path_resolve "$1") [[ -z "${SOURCES["$path"]}" ]] && { SOURCES["$path"]=true . "$path" return 0 } #Warn if a second `source` is attempted from the main scope of an interactive session [[ -z "${BASH_SOURCE[0]}" ]] && { warn "$path already sourced in" warn "Use \`. '$1'\` to reload it" } return 1 } #AKA source_relative_once AKA include_relative_once #require relative to current file or $PWD if there no current file require_relative() { local dir="${BASH_SOURCE%/*}" [[ -z "$dir" ]] && dir="$PWD" require "$dir/$1" } #source relative to current file or $PWD if there no current file source_relative() { local dir="${BASH_SOURCE%/*}" [[ -z "$dir" ]] && dir="$PWD" source "$dir/$1" } 
0
source

Source: https://habr.com/ru/post/988537/


All Articles