Search code examples
bashenvsubst

Replace value of an environment variable declared in a file


There is a file env.sh, which defines environment variables:

$cat env.sh
export var1=1
export var2=2

I want to replace the value of var1 inside of the file with 3, so that

$cat env.sh
export var1=3
export var2=2

Is there way to do it without string/regexp matching magic?

I read a lot about envsubst, but still was not able to figure out how to apply it to the task.


Solution

  • Just use a scriptable editor like ed:

    $ cat env.sh
    export var1=1
    export var2=2
    $ printf  '/var1=/s/=.*/var1=3/\nw\n' | ed env.sh
    28
    28
    $ cat env.sh
    export var1=3
    export var2=2