How to override local variable by environment variable

10,051

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

Share:
10,051

Related videos on Youtube

Mahibarauniya
Author by

Mahibarauniya

Updated on September 18, 2022

Comments

  • Mahibarauniya
    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 use 20181212 from this script. But each time its picking the value as 20181214.

    • muru
      muru over 5 years
      Can you modify the script?
  • Stéphane Chazelas
    Stéphane Chazelas over 5 years
    Depending on the interpreter, there are possible hack approaches like with $BASH_ENV/~/.zshenv where you could add some DEBUG traps, or bash'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 the a=20181214 assignment.