Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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

like image 450
JN_newbie Avatar asked Sep 11 '25 01:09

JN_newbie


1 Answers

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.

like image 67
Pierre François Avatar answered Sep 13 '25 19:09

Pierre François