0

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.

1
  • If there's already a value set, do you want to remove it and replace it with the new value? Commented Jan 27, 2014 at 16:11

1 Answer 1

1

You can use grep:

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

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

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

3 Comments

There is a race condition if multiple instances of this script could be running simultaneously. This is hard to fix with just shell script.
Oh of course most of the shell scripts are not written with that requirement in place. However if there is any chance like that then creating a temporary .pid file might help.
Fixing race conditions in scripts is trivial with flock.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.