Home > Mobile >  Dot env file comparison/validation
Dot env file comparison/validation

Time:04-10

If you have multiple .env files in a given directory for specific environments e.g. dev.env, staging.env and prod.env, using a shell, is it possible to check that each file has the same env var keys, ignoring the values?

For example, given the following files:

dev.env

KEY_1=DEV_VALUE_1
KEY_2=DEV_VALUE_2

staging.env

KEY_1=STAGING_VALUE_1
KEY_2=STAGING_VALUE_2

prod.env

KEY_1=PROD_VALUE_1
KEY_2=PROD_VALUE_2
KEY_3=PROD_VALUE_3

Can anyone suggest an awk command or similar that would return a non-zero exit code due to prod.env containing an extra key? The goal here is to validate that all .env files are aligned in the keys they declare, primarily in a CI setting.

CodePudding user response:

Sure, count the files for each key, and show discrepancies.

#! /usr/bin/awk -f

{
    keys[$1]  
}

END {
    for( key in keys ) {
        if( n == 0 ) {
            n = keys[key]
        }

        if( keys[key] != n ) {
            printf "%s appears in %d of %d files\n", \
            key, keys[key], n > "/dev/stderr"
        }
    }
}
$ awk -F= -f ./missing.awk *.env
KEY_3 appears in 1 of 3 files
  • Related