Issue
I have an .env.branch
file with the following structure -
SOME_URL=https://somelink.com
SOME_OTHER_URL=https://someotherlink.com
SOME_FLAG=true
SOME_OTHER_OPTION=0
BRANCH_NAME=
My goal is to write a bash
script that replaces the BRANCH_NAME
config based on an environment variable called BRANCH_NAME
(the number of lines in the config isn't fixed). This is how I am currently doing it -
echo "BRANCH_NAME=/"$BRANCH_NAME >> .env.branch
but all this does is append the line every time I run the bash script. So now I have -
SOME_URL=https://somelink.com
SOME_OTHER_URL=https://someotherlink.com
SOME_FLAG=true
SOME_OTHER_OPTION=0
BRANCH_NAME=
BRANCH_NAME=/somebranch
BRANCH_NAME=/somebranch
How can I achieve this using sed
or some other bash feature?
Solution
This should replace your last line with whatever new BRANCH_NAME
you have, and save it. Just place the line in your bash script or enter it manually. Both work.
sed -i "s/BRANCH_NAME=.*/BRANCH_NAME=${BRANCH_NAME}/" .env.branch
Result:
> mkdir sed
> nano .env.branch
> BRANCH_NAME=some_branch
> cat .env.branch
SOME_URL=https://somelink.com
SOME_OTHER_URL=https://someotherlink.com
SOME_FLAG=true
SOME_OTHER_OPTION=0
BRANCH_NAME=
> sed -i "s/BRANCH_NAME=.*/BRANCH_NAME=${BRANCH_NAME}/" .env.branch
> cat .env.branch
SOME_URL=https://somelink.com
SOME_OTHER_URL=https://someotherlink.com
SOME_FLAG=true
SOME_OTHER_OPTION=0
BRANCH_NAME=some_branch
Answered By - Nizar Answer Checked By - Katrina (WPSolving Volunteer)