'How to declare a var in bash without it replacing a var in a different file

I have 2 files file1 and file2. Inside file1 I declare a var, x=1. In file2 I make a var x=2. If I run file one then file two, and then in the shell echo x, I get x=2. How would I access the x=1 from file1 when I need to and then access the x=2 from file 2 if I need to.



Solution 1:[1]

If you call file2 from file you'd like to export x in file1 It would be something like this:

file1.sh

#!/bin/bash
export x=1
echo "$x from $0"
./file2.sh

echo "$x from $0"

file2.sh

#!/bin/bash
x=2
echo "$x from $0"

Output will be

$ ./file1.sh 
1 from ./file1.sh
2 from ./file2.sh
1 from ./file1.sh
$ 

If you call file1.sh and file2.sh separately then x must be declared previous to file1.sh execution.

In this example x is undefined, then it is exported as a global variable, and youc an see its value from the second echo:

$ echo $x

$ export x=1
$ echo $x
1
$

If lines containing declaration of x and call to file2.sh are removed form file1.sh, then you'll see file1.sh inherits the value of x. But it is overridden in file2.sh.

Once file2.sh execution finishes the value of x remains 1:

$ ./file1.sh 
1 from ./file1.sh
$ ./file2.sh 
2 from ./file2.sh
$ echo $x
1
$

You can try exporting x=3 in the shell and using file1.sh and file2.sh as in first example then you'll see something like this:

$ export x=3; echo $x; ./file1.sh ; echo $x
3
1 from ./file1.sh
2 from ./file2.sh
1 from ./file1.sh
3
$

Regards

Solution 2:[2]

In file2.sh, instead of doing x=2, you can write it like : ${x=2}.

Demo -

# Creating the files
$ echo x=1 > file1.sh
$ echo ': ${x=2}' > file2.sh
# Running both files
$ . file1.sh
$ . file2.sh
$ echo $x
1
# See? the output is 1, which was set by file1.sh
# Now, if you want to get the value of x from file2.sh -
$ unset -v x
$ . file2.sh
$ echo $x
2
# See? the output is 2, which was set by file2.sh
$ . file1.sh
$ echo $x
1
# See? x was over-written by file1.sh

Contents of file1.sh in above demo -

x=1

Contents of file2.sh in above demo -

: ${x=2}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 snath03