Is there a way to validate a .env file?
Asked Answered
ini
W

2

9

I'm getting errors when trying to parse a .env file I have, but I have no way of figuring out where it's erring out. Is there an easy way to lint/validate the file, online or otherwise?

Many thanks!

Whitewash answered 25/5, 2017 at 22:29 Comment(0)
M
4

You can try https://github.com/dotenv-linter/dotenv-linter. It's a lightning-fast linter for .env files. Written in Rust.

Mekka answered 1/1, 2020 at 18:10 Comment(0)
Q
0

It depends on the syntax you are using. Looking at the Docker and NPM documentation, different tools seem to have a different scope on what they are able to parse.

I use a simple grep to validate if I have a <key>=<value> pattern, where key and value are non-empty. You can adapt the patterns to match your context, ensuring upper case keys for example.

#!/bin/bash

for envfile in $(find . -maxdepth 1 -type f -name '.env.*'); do 
    for line in $(cat ${envfile}); do
        # exclude comments
        if [[ "${line:0:1}" == "#" ]]; then
            continue
        fi

        match_line=$(echo ${line} | grep -E "^[A-Za-z0-9_].+=.+$")

        if [[ ${match_line} == "" ]]; then
            echo "Error in file: ${envfile}: line: ${line}"
        fi
    done
done

Alternatively, look at your language loadenv library to see if you can catch specific parsing exceptions, if available, to narrow down the specific line that causes the error.

Quadriceps answered 31/5, 2019 at 11:34 Comment(1)
I found this useful but this does not work with string value that has space. You should change this line for line in $(cat ${envfile}); do to while IFS= read -r line; ... to not trim the spaceTyrant

© 2022 - 2024 — McMap. All rights reserved.