1

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I use source set.sh -> ./set.sh 1 -> ./get. No result.
Have your scripts exactly as I wrote in my answer. Then do: source ./set.sh 222 followed by ./get.sh
There is no way put source into set.sh script?
You can put source command in set.sh but unfortunately source will be done in a sub shell. Just understand that when you run a script as ./.set.sh it is executed in sub-shell and all the changes made in sub-shell are not reflected in parent (current) shell.
1

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

Comments

0

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.

1 Comment

I have script A, and autocomplete script for this script B. Scripts B and A use same conf file. I need way to change path to conf file in both script (path in variable). source B is already done. So i need way change variable of B script in A script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.