Reputation: 1767
What better way to use same variable in two different bash scripts?
Simple example:
./set.sh 333
./get.sh
> 333
./set.sh 111
./get.sh
> 111
And how initialize that variable first time?
UPD:
$ cat get.sh
echo "$var"
$ cat set.sh
export var="$1"
$ chmod +x set.sh get.sh
$ source set.sh
$ ./set.sh u
$./get.sh
$ source ./set.sh 2
$ ./get.sh
2
Upvotes: 1
Views: 322
Reputation: 7851
What you need to understand is the lifetime of a shell variable (or an environment variable as you are using).
When you run a sub-shell, you are running a child process of the shell, and any shell variables that you set exist for the lifetime of the script. Any environment variables (shell variables are "promoted" to environment variable by the use of export
) are copied into the environment of the child process - so changes to environment variables in a child process have NO effect on the value in the parent process.
So what you need to use is source
which executes the contents of the script in the current shell (no sub-shell is spawned). Always source
set.sh
and you should be OK
Upvotes: 1
Reputation: 785581
You can have your scripts as:
cat set.sh
export var="$1"
cat get.sh
echo "$var"
chmod +x set.sh get.sh
Then call them:
. ./set.sh 333
./get.sh
333
Please note that . ./set.sh
OR source ./set.sh
is called sourcing in the script which makes sure that set.sh
is executed without creating a sub-shell and variables set in that script are accessible in the other scripts.
Upvotes: 1
Reputation: 26555
You have to store that number in a file.
A called shell script is not able to change the variables of the calling shell.
Another way is to source the shell script instead of running it as a separate process.
But maybe you should explain why you think, that you need that feature. Maybe some totally different solution is even better.
Upvotes: 0