Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script for merging dotenv files with duplicate keys

Given two dotenv files,

# file1
FOO="X"
BAR="B"

and

# file2
FOO="A"
BAZ="C"

I want to run

$ ./merge.sh file1.env file2.env > file3.env

to get the following output:

# file3
FOO="A"
BAR="B"
BAZ="C"

So far, I used the python-dotenv module to parse the files into dictionaries, merge them and write them back. However, I feel like there should be a simple solution in shell that rids myself of a third-party module for such a basic task.


Answer

Alright, so I ended up using

$ sort -u -t '=' -k 1,1 file1 file2 | grep -v '^$\|^\s*\#' > file3

which omits blank lines and comments. Nevertheless, the proposed awk solution works just as fine.

like image 294
beltakufyu Avatar asked Aug 28 '19 11:08

beltakufyu


People also ask

Can you have 2 .env files?

One solution is to have multiple . env files which each represent different environments. In practice this means you create a file for each of your environments: .

Does dotenv overwrite?

By default, it won't overwrite existing environment variables as dotenv assumes the deployment environment has more knowledge about configuration than the application does. To overwrite existing environment variables you can use Dotenv. overload.

How do you preload dotenv?

Preload. You can use the --require ( -r ) command line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. This is the preferred approach when using import instead of require .

Is .env safe for production?

env files are simply too risky and cumbersome for modern application development. While . env files are still commonly used and were an improvement upon storing secrets in source code, the security risks and impact on developer productivity are only now being fully realized.


2 Answers

Another quite simple approach is to use sort:

sort -u -t '=' -k 1,1 file1 file2 > file3

results in a file where the keys from file1 take precedence over the keys from file2.

like image 200
Daniel Avatar answered Sep 25 '22 08:09

Daniel


Using a simple awk script:

awk -F= '{a[$1]=$2}END{for(i in a) print i "=" a[i]}' file1 file2

This stores all key values in the array a and prints the array content when both files are parsed.

The keys that are in file2 override the ones in file1.

like image 40
oliv Avatar answered Sep 25 '22 08:09

oliv