Last active
March 14, 2024 10:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for the script, but it doesn't work when .env is empty