A simple way to retrieve, update, or delete .env variables directly from the command line.
npm i -g @mikegarde/dotenv-cli
Get a value from a .env file:
dotenv <key>
Get a value from a .env.example file:
dotenv <key> --file .env.example
By 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:
dotenv
Wildcard 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+CqvjWYzvQwECAwEAAQJAIJLixBy2qpFoS4DSmoEm
Set 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> --delete
- Private Key: Generate a new key using the
openssl
command. The private key is then stored in the .env file under the variableRSA_KEY
. - Public Key The
dotenv
command, with the--multiline
flag, retrieves the stored private key and pipes it back to openssl.openssl
then generates a corresponding public key. This public key is stored in the.env
file 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_PUB
This 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_VERSION
Make it pretty with jq
:
dotenv --json | jq
Or filter the output:
$ dotenv --json | jq 'to_entries | map(select(.key | startswith("DB_")))[] | "\(.key)=\(.value)"'
"DB_HOST=localhost"
"DB_USER=root"
"DB_PASS=password"