by Oliver; 2014
30. source, export
From
An Introduction to the Command-Line (on Unix-like systems) - Source and Export:
Question: if we create some variables in a script and exit, what happens to those variables?
Do they disappear?
The answer is, yes, they do.
Let's make a script called
test_src.sh such that:
$ cat ./test_src.sh
#!/bin/bash
myvariable=54
echo $myvariable
If we run it and then check what happened to the variable on our command line, we get:
$ ./test_src.sh
54
$ echo $myvariable
The variable is undefined.
The command
source is for solving this problem.
If we want the variable to persist, we run:
$ source ./test_src.sh
54
$ echo $myvariable
54
and—voilà!—our variable exists in the shell.
An equivalent syntax for sourcing uses a dot:
$ . ./test_src.sh # this is the same as "source ./test_src.sh"
54
But now observe the following.
We'll make a new script,
test_src_2.sh, such that:
$ cat ./test_src_2.sh
#!/bin/bash
echo $myvariable
This script is also looking for
$myvariable.
Running it, we get:
$ ./test_src_2.sh
Nothing!
So
$myvariable is defined in the shell but, if we run another script, its existence is unknown.
Let's amend our original script to add in an
export:
$ cat ./test_src.sh
#!/bin/bash
export myvariable=54 # export this variable
echo $myvariable
Now what happens?
$ ./test_src.sh
54
$ ./test_src_2.sh
Still nothing!
Why?
Because we didn't
source test_src.sh.
Trying again:
$ source ./test_src.sh
54
$ ./test_src_2.sh
54
So, at last, we see how to do this.
If we want access on the shell to a variable which is defined inside a script, we must
source that script.
If we want
other scripts to have access to that variable, we must
source plus
export.
<PREV
NEXT>