Search code examples
bashsedgrepenvironment-variables

Bash command to parse .env file contains equal (=) sign in values


I have a .env file,

# Some variables
USERNAME=user1
PASSWORD=

# Other variables
URL=https://example.com
TOKEN=muDm8qJ6mqM__YX024dk1RXluPnwd-3mxyt1LwLoI4ISiVPA==

Purpose

My purpose is to create one line bash command to print each non-empty variables in <name> <value> format, which shall

  1. Print one line for each variable with [space] between name and value;
  2. Ignore comments;
  3. Ignore variables with no value;

Expected output

The expected output is,

USERNAME user1
URL https://example.com
TOKEN muDm8qJ6mqM__YX024dk1RXluPnwd-3mxyt1LwLoI4ISiVPA==

Current Solution

My current solution is as following,

grep -v '^#' .env | grep -v '^[[:space:]]*$' | grep -v '=$' | sed 's/=/ /' | while read -r line; do echo $line; done

Actual output

USERNAME user1
URL https://example.com

It only prints out the first two lines, the issue with last line is caused by the equal (=) signs in TOKEN value.

Help needed

Anyone can help me to rectify the command? also welcome if there is easier way to achieve the goal.


Solution

  • Using sed

    $ sed '/=\</!d;s/=/ /' input_file
    USERNAME user1
    URL https://example.com
    TOKEN muDm8qJ6mqM__YX024dk1RXluPnwd-3mxyt1LwLoI4ISiVPA==
    

    Delete lines that do not match a valid variable i.e have no inpurt after =, this will also match blank lines and for your example data, lines with comments as there is no valid variable on the line. Finally, replace the first occurance of the = equal character for a space.