How to override local variable by environment variable
Solution 1
If you can modify the script then modify it so that it says
a=${a:-20181214}
This would make it use the previously set value of a
, or 20181214
if $a
is empty or the variable is unset. This is a standard parameter expansion.
You would then either use
export a=20181212
./script.sh
or
a=20181212 ./script.sh
The latter of these avoids setting the variable in the calling environment and only sets it for the script's environment.
If you can't modify the script, then the script would always override your a
value, no matter what you did. In this case, contact the person who maintains the script and explain the situation. If worse comes to worse, use a copy of the script that you can modify, assuming the script does not expect to be located in a particular location.
Solution 2
A script will be executed within another shell. And the command export A
only sets the variable for the current shell.
You could export the variable on top of your script, it wouldn't affect the rest of your environment. Eg
~$ export A=a
~$ echo $A
a
if you create in the same shell a script test.sh
#!/bin/bash
export A=b
echo $A
The output will be 'b', but value of A in the shell remains unchanged
Related videos on Youtube
Mahibarauniya
Updated on September 18, 2022Comments
-
Mahibarauniya almost 2 years
I have one script running in production where one value assigns but i want to use a different value from here.
My script.sh
a=20181214 ....
I was calling this script after
export a=20181212
and then call this script as i want to use20181212
from this script. But each time its picking the value as20181214
.-
muru over 5 yearsCan you modify the script?
-
-
Stéphane Chazelas over 5 yearsDepending on the interpreter, there are possible hack approaches like with
$BASH_ENV
/~/.zshenv
where you could add some DEBUG traps, orbash
's exported functions where you could redefine a command used in the script to reset the value of the variable to the one the OP wants after it has run thea=20181214
assignment.