JN_newbie
JN_newbie

Reputation: 6062

How to remove or replace the key value from .env using bash script

I am trying to remove the value or replace the value in .env file using bash script

in my .env file I have

TEST_VAR=testVariable

I have inserted this TEST_VAR using bash script using the below script

#!/bin/bash
echo TEST_VAR="testVariable" >> .env

The problem is if I run the bash script again it will enter TEST_VAR multiple times in .env. How can I replace the value or may be remove this key pair value.

for example

If I run again the bash script with changed value

#!/bin/bash
echo TEST_VAR="updateValue" >> .env

it should show in .env file

TEST_VAR=updatedValue

rather than below

TEST_VAR=testVariable TEST_VAR=updatedValue

Upvotes: 4

Views: 6517

Answers (1)

Pierre François
Pierre François

Reputation: 6061

Try this, assuming the .env you want to update is file.env:

sed -i~ '/^TEST_VAR=/s/=.*/="UpdateValue"/' file.env

Explanation: the command sed -i~ is able to edit a file in place; i.e. without the need to make a copy. The old version of the file will go to file.env~.

The command s/=.*/="UpdateValue"/ changes everything after the = to ="UpdateValue". The command applies only to lines beginning with TEST_VAR= which is expressed by prepending the regex /^TEST_VAR=/ to the sed command above.

Upvotes: 12

Related Questions