Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I source_once in bash?

Tags:

bash

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.

like image 715
PSkocik Avatar asked Jun 04 '15 21:06

PSkocik


People also ask

How do you source a file in bash?

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.

How do you source a file in shell?

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.

How do I import a file into a bash script?

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.


1 Answers

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.

Alternate Approach

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
like image 143
John1024 Avatar answered Oct 07 '22 00:10

John1024