Skip to content

Instantly share code, notes, and snippets.

@flaki
Last active March 14, 2024 10:42
Show Gist options
  • Save flaki/a42e4cda13089cce073089d05114fc94 to your computer and use it in GitHub Desktop.
Save flaki/a42e4cda13089cce073089d05114fc94 to your computer and use it in GitHub Desktop.
sed script for updating a variable in place or appending it to an existing .env file
# Script for updating a var in an .env file
# (will add it to the end of the file, if not found)
sed -in '
# If a line contains our variable, continue at :set
s/^ENV_VAR=.*$//; t set
# Otherwise if this is the last line, check the hold space
# If hold space is empty, no substitution occured, we need
# to manually add the line at the end of the .env file
$ { x; /^$/ { x; p; b set }; d }
# Just print non-matching lines
p;d
# Reuse the same code to make the change/append the value
:set
# Change current line to updated value
# Store a sentinel value on the hold space to track
# substitution so we skip adding a duplicate line at the end
s/.*/ENV_VAR=newvalue/p; h; d' .env
# sed documentation/resources used:
# - https://www.grymoire.com/unix/Sed.html
# - https://linuxhandbook.com/sed-reference-guide/
@flaki
Copy link
Author

flaki commented Feb 15, 2021

Updated script (line #9) to fix the last line being accidentally overwritten when the variable is not already in the file.

@ccxuy
Copy link

ccxuy commented Mar 14, 2024

thanks for the script, but it doesn't work when .env is empty

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment