How to declare variables once and reuse them in other scripts?

Hello everyone.

I'm trying to create a conf file with variables that my other scripts will use.

I have several scripts that use the same variables, and since I don't know how to read them from an external file, i define them in each script (and then if i want to change one's value i need to change it separately in each script.)

so i'm trying to create a conf file that will look like that:

var1="aaa"
var2="bbb"
etc...

and then within each script refer to this file:

var1= (var 1 from external conf file)
var2 = (var 2 from external conf file)

I'd appreciate any guidance in this regard,

Thanks
Moshe

Hi.

Put all your declarations in a separate file, and then source that file in your other scripts.

i.e.

$ cat /Users/scott/myVars.sh
var1=123
var2=abc

$ cat myScript
. /Users/scott/myVars.sh
echo var1 is $var1
echo var2 is $var2

$ ./myScript
var1 is 123
var2 is abc

Thanks Scott.
I just tried it and it seems to work.
Which is way simpler then i thought (:

so by typing . /(filename)
i add the content of the file to the script?
or what does . / exactly do?

Forget the /, that's part of the filename.

The important thing is the dot (.), or you can use the word source, if you prefer.

From the bash man-page:

        .  filename [arguments]
       source filename [arguments]
              Read and execute commands from filename in the current shell environment and return the exit  status  of
              the  last  command executed from filename.  If filename does not contain a slash, file names in PATH are
              used to find the directory containing filename.  The file searched for in PATH need not  be  executable.
              When  bash  is not in posix mode, the current directory is searched if no file is found in PATH.  If the
              sourcepath option to the shopt builtin command is turned off, the PATH is not searched.   If  any  argu-
              ments  are  supplied,  they  become  the positional parameters when filename is executed.  Otherwise the
              positional parameters are unchanged.  The return status is the status of the last command exited  within
              the script (0 if no commands are executed), and false if filename is not found or cannot be read.
1 Like

Awsome! thanks!!