0

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.

6
  • 1
    I'm confused. Can you not just edit the file and replace the value? What distro are you using? You may also be able to edit a .bashrc or .bash_profile and simply overwrite the value of var1 Commented Aug 21, 2019 at 12:51
  • @jasonmclose I could. However this step should be a bash command. The value of var1 is generated as part of the process and as soon as it is generated it needs to be replaced in a file. Commented Aug 21, 2019 at 12:53
  • Not very elegant, append a new line: echo "export var1=3" >> env.sh Commented Aug 21, 2019 at 12:53
  • Thank you, that is an option. I want to have only one definition of var1 in the file though Commented Aug 21, 2019 at 12:55
  • 1
    This is just a file-editing task. Use an editor like ed, sed, or ex. Commented Aug 21, 2019 at 13:18

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.