What's a good way of sourcing in just once in bash.
Does bash store the paths of the files that have been sourced in or do I need to make all source
/.
invocations go through a wrapper that will store those paths?
Is there a standardly available mechanism that will find what a source argument resolves to? which
doesn't seem to work unless the file is executable.
The built-in bash source command reads and executes the content of a file. If the sourced file is a bash script, the overall effect comes down to running it. We may use this command either in a terminal or inside a bash script. To obtain documentation concerning this command, we should type help source in the terminal.
A file is sourced in two ways. One is either writting as source <fileName> or other is writting as . ./<filename> in the command line. When a file is sourced, the code lines are executed as if they were printed on the command line.
There are two ways to import files in bash, and both do the exact same thing, they just have different syntax. You can use the source command to import a file. …or you can also use a period. Sourcing is done when bash first starts when you open a terminal or ssh into a server using the bash shell.
In each of your files that you might source, add a statement. Suppose that the file /etc/interface
is one of the files that you want to only source once, then format that file as follows:
if [ ! "$ETC_INTERFACE" ]
then
# statements that you
# want to source...
fi
export ETC_INTERFACE=Yes
This assures that the statements in /etc/interface
are only executed once. If a script tries to source it again, it will see that ETC_INTERFACE
has been set and skip the body of the file.
Suppose that one does not want to modify the files that are to be sourced but it is OK to modify the scripts which source them. In that case, source them as follows:
[ ! "$ETC_INTERFACE" ] && source /etc/interface && export ETC_INTERFACE=Yes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With