在源文件中查找并替换环境变量的值

时间:2022-04-09 23:02:06

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.

这只是附加一条线,经过几次运行后,有多条线具有diff值。我可以在一次运行程序后删除此文件,但这不是确定的。

1 个解决方案

#1


1  

You can use grep:

你可以使用grep:

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

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

当grep返回非成功返回码时,echo将执行。

#1


1  

You can use grep:

你可以使用grep:

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

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

当grep返回非成功返回码时,echo将执行。