A simple way to retrieve, update, or delete .env variables directly from the command line.
npm i -g @mikegarde/dotenv-cliGet a value from a .env file:
dotenv <key>Get a value from a .env.example file:
dotenv <key> --file .env.exampleBy default multiple keys are returned as a JSON object. To return a single key as a JSON object, use the --json flag.
To not return a JSON object, use the --no-json flag.
Return a .env file as JSON:
dotenvWildcard search:
dotenv "DB_*"The default behavior is to output a single line value. If you want to output a multiline value,
you can use the --multiline flag:
$ dotenv RSA_KEY
-----BEGIN RSA PRIVATE KEY-----\nMIIBOgIBAAJBAKj34GkxFhD90vcNLYLInFEX6Ppy1tPf...
$ dotenv RSA_KEY --multiline
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBAKj34GkxFhD90vcNLYLInFEX6Ppy1tPf9Cnzj4p4WGeKLs1Pt8Qu
KUpRKfFLfRYC9AIKjbJTWit+CqvjWYzvQwECAwEAAQJAIJLixBy2qpFoS4DSmoEmSet a value in a .env file:
dotenv <key> --set <value>Or pipe a value in:
echo <value> | dotenv <key>Delete a value from a .env file:
dotenv <key> --deleteYou can define the DOTENV_FILE environment variable in your shell or script to specify the .env file to use, instead
of passing the --file option every time.
export DOTENV_FILE=.env.example
dotenv <key>This will use the .env.example file automatically. If the --file option is provided, it will override the
DOTENV_FILE environment variable.
- Private Key: Generate a new key using the
opensslcommand. The private key is then stored in the .env file under the variableRSA_KEY. - Public Key The
dotenvcommand, with the--multilineflag, retrieves the stored private key and pipes it back to openssl.opensslthen generates a corresponding public key. This public key is stored in the.envfile under the variableRSA_PUB.
openssl genpkey -algorithm RSA -outform PEM -pkeyopt rsa_keygen_bits:2048 2>/dev/null | dotenv RSA_KEY
dotenv RSA_KEY -m | openssl rsa -pubout 2>/dev/null | dotenv RSA_PUBThis demonstrates two methods for updating the APP_VERSION in your .env file. The sed command is versatile and powerful, allowing for complex text manipulations. On the other hand, dotenv provides a more readable and straightforward syntax.
NEW_VERSION=3.22.1
# Using sed
sed -i "s/^APP_VERSION=.*$/APP_VERSION=$NEW_VERSION/" .env
# Using dotenv
dotenv APP_VERSION --set $NEW_VERSIONMake it pretty with jq:
dotenv | jqOr filter the output:
$ dotenv | jq 'to_entries | map(select(.key | startswith("DB_")))[] | "\(.key)=\(.value)"'
"DB_HOST=localhost"
"DB_USER=root"
"DB_PASS=password"