user1071840
user1071840

Reputation: 3592

Find and replace value of an environment variable in source file

I have a file which has environment variable listed like

 VAR_NAME=abc

and this file is sourced when needed. I want to add a new environment variable to the file if it's not present already. How do I search this file and replace/add a new value to it?

I was doing this till now:

echo "string_created" >> fileName

this just appends a line and after few runs there were multiple lines with diff values. I can remove this file after one run of my program but that isn't definitive.

Upvotes: 0

Views: 792

Answers (1)

anubhava
anubhava

Reputation: 785058

You can use grep:

grep -q '^VAR_NAME=' file || echo 'VAR_NAME=abc' >> file

echo will execute when grep returns non-success return code.

Upvotes: 1

Related Questions