Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables between files in shell / bash scripting

Tags:

bash

shell

This question has been posted here many times, but it never seems to answer my question.

I have two scripts. The first one contains one or multiple variables, the second script needs those variables. The second script also needs to be able to change the variables in the first script.

I'm not interested in sourcing (where the first script containing the variables runs the second script) or exporting (using environment variables). I just simply want to make sure that the second script can read and change (get and set) the variables available in the first script.

(PS. If I misunderstood how sourcing or exporting works, and it applies to my scenario, please let me know. I'm not completely closed to those methods, after what I've read, I just don't think those things will do what I want)

like image 549
Timmiej93 Avatar asked Nov 22 '25 12:11

Timmiej93


2 Answers

Environment variables are per process. One process can not modify the variables in another. What you're asking for is not possible.

The usual workaround for scripts is sourcing, which works by running both scripts in the same shell process, but you say you don't want to do that.

like image 94
that other guy Avatar answered Nov 24 '25 03:11

that other guy


I've also given this some thought. I would use files as variables. For example in script 1 you use for writing variable values to files:

echo $varnum1 > /home/username/scriptdir/vars/varnum1
echo $varnum2 > /home/username/scriptdir/vars/varnum2

And in script 2 you use for reading values from files back into variables:

$varnum1=$(cat /home/username/scriptdir/vars/varnum1)
$varnum2=$(cat /home/username/scriptdir/vars/varnum2)

Both scripts can read or write to the variables at any given time. Theoretically two scripts can try to access the same file at the same time, I'm not sure what exactly would happen but since each file only contains one value, the time to read or write should be extremely short. In order to even reduce those times you can use a ramdisk.

I think this is much better than scripts editing each other (yuk!). Live editing of scripts can mess up scripts and only works when you initiate the script again after the edit was made.

Good luck!

like image 30
Mike Avatar answered Nov 24 '25 03:11

Mike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!