Replace value of an environment variable declared in a file

1.2k Views Asked by At

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.

2

There are 2 best solutions below

0
chepner On BEST ANSWER

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
0
Cyrus On

Without regex in a script:

#!/bin/bash
source env.sh
export var1=3
declare -p var1 > env.sh
declare -p var2 >> env.sh

Output to env.sh:

declare -x var1="3"
declare -x var2="2"

declare -x is synonymous with export.