Created
August 19, 2022 17:24
-
-
Save seppestas/38bbc8e33d1406dd495252a9305d9e0b to your computer and use it in GitHub Desktop.
Parses a .env files with Windows commander (cmd)
This file contains hidden or 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
:: Parses a .env file with windows cmd similar to Posix source | |
:: Note: This only works for oneliners when delayed varaible extension is used | |
:: e.g with cmd /V:ON | |
:: Pass the /F flag to overwrite existing variables | |
@echo off | |
setlocal enabledelayedexpansion | |
set envfile=.env | |
set force=0 | |
FOR %%A IN (%*) DO ( | |
IF "%%A"=="/F" ( | |
set force=1 | |
) ELSE ( | |
set envfile=%%A | |
) | |
) | |
:: Use the Windows native `for` command to set each variable in a .env file | |
:: Remove lines starting with # | |
:: Remove everything after # | |
:: Store everything before = in %c, everything after = in %d | |
:: Store everything after the first quote (assumed to be in between quotes) or | |
:: anything not in qoutes in %e | |
FOR /F "eol=# delims=" %%a IN (%envfile%) DO ( | |
FOR /F "delims=#" %%b IN ("%%a") DO ( | |
FOR /F "tokens=1,2 delims==" %%c IN ("%%b") DO ( | |
FOR /F usebackq^ tokens^=1^,2^ delims^=^" %%e IN ('%%d') DO ( | |
IF %force%==1 ( | |
set %%c=%%e | |
) ELSE ( | |
IF DEFINED %%c ( | |
echo %%c already set to "!%%c!" in environment. Use /F to overwrite. | |
) ELSE ( | |
set %%c=%%e | |
) | |
) | |
) | |
) | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment