S
S
Stanislav2019-11-20 10:57:12
linux
Stanislav, 2019-11-20 10:57:12

How to edit .env file most natively?

There is a .env file, it stores some values ​​in the usual format for this file:

ENV_VAR_1=123
ENV_VAR_2=456
ENV_VAR_3=789

It is necessary as natively as possible for linux, that is, if possible, with the help of some commands responsible for this, change the value of one of the variables. So that we end up with a file like this:
ENV_VAR_1=321 # изменено
ENV_VAR_2=456
ENV_VAR_3=789

It should be taken into account that variables can be framed from above, below or to the right by comments, that they may not be in the file at all (then it is worth adding the variable to its end), and so on.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
R
Ruslan Fedoseev, 2019-11-20
@martin74ua

ansible
in specific case - lineinfile module

N
Nujabes37, 2019-11-20
@Nujabes37

What if the value of the variable is unknown?

And by analogy, ENV_VAR_2, etc. only the number - 1 after the backslash, do not delete it, it is needed to return the first match from the regular expression)
Nothing bad will happen
Provided in the regular season, you can check

S
Saboteur, 2019-11-20
@saboteur_kiev

sed and basic regex ownership is what you need.
Change a line, add, delete, right in the file.
Display filename on the screen with the changes made.
Actually save the changes made to the file itself.
Most often sed is used with the "s" (replacement) command, e.g.
sed -ir "s/ENV_VAR_1=.*/ENV_VAR_1=321/" dev.env

C
CityCat4, 2019-11-20
@CityCat4

Why mess around like that? mcedit/nano/vim - our everything

M
mozilla, 2020-12-26
@mozilla

Who will search - sketched a script

#!/bin/bash
name=$1
value=$2
envfile=$3

if [ "$envfile" == "" ]; then
    envfile=~/.env
fi


if [ ! -e $envfile ]; then
    touch $envfile
fi

have=$(grep $name $envfile)
if [ "$have" == "" ]; then
    echo "$name=$value" >> $envfile
else
    sed -ir "s/$name=.*/$name=$value/" $envfile
    rm -f ${envfile}r
fi

works like ./env_set.sh ENV_VAR_1 321 .env

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question