Search code examples
bashawksedenvironment-variables

How to save environment variables with newlines into .env file?


I'm probably missing something here but I'm trying to save environment variables with newlines into a .env file. Ideally I want to do this with all available env variables (output of env).

Take this variable:

export MY_VAR="Line 1
Line 2
Line 3"

How do I save this in a .env file that would look like: variables.env

MY_VAR=Line 1\nLine2\nLine3

And how can I do this with all available env variables, like from env? I tried this:

while IFS= read -r -d '' line; do
    line=$(echo -n "$line" | sed '$!s/$/\\n/' | tr -d '\n')
    echo "$line" >> variables.env
done < <(env -0)

But this also doesn't work for \r.


Solution

  • This might be good enough for whatever it is you're trying to do:

    $ cat tst.sh
    #!/usr/bin/env bash
    
    export MY_VAR="Line 1
    Line 2
    Line 3"
    
    export MY_VAR2=17
    
    regexp="^[$]?'(.*)'$"
    while IFS= read -r -d '' line; do
        printf -v line '%q' "$line"
        # or you could do this if your bash version is 4.4 or newer:
        #    line="${line@Q}"
        if [[ "$line" =~ $regexp ]]; then
            line="${BASH_REMATCH[1]}"
        fi
        printf '%s\n' "$line"
    done < <(env -0)
    

    $ ./tst.sh | grep MY_VAR
    MY_VAR=Line 1\nLine 2\nLine 3
    MY_VAR2=17