Home > Back-end >  shell commands to convert environment variables into export commands
shell commands to convert environment variables into export commands

Time:12-09

I have a file, that is created by doing "env > env.sh"

$ cat env.sh
X=1
Y=2
Z=3
ABCD=/var/tmp
SSH_CONNECTION=192.168.31.1 21905 192.168.31.3 22

I want to convert this to export commands on every line, i.e.

$ cat env_out.sh
export X="1"
export Y="2"
export Z="3"
export ABCD="/var/tmp"
export SSH_CONNECTION="192.168.31.1 21905 192.168.31.3 22"

How do I do this using just linux shell commands? I have a bash script (see below) to do this - but i want to be able to do it with command line commands..

while IFS= read -r i;
do
    KEY=`echo $i | cut -f1 -d'='`
    VALUE=`echo $i | cut -f2 -d'='`
    echo "export $KEY=\"$VALUE\""
done < env.sh

CodePudding user response:

If you know for a fact that every line in env.sh is a valid variable assignment then a simple sed should suffice:

$ sed 's/^/export /' env.sh
export X=1
export Y=2
export Z=3
export ABCD=/var/tmp
export SSH_CONNECTION=192.168.31.1 21905 192.168.31.3 22

On the other hand, if env.sh contains commented lines, blank lines, multi-line values, etc, then it gets a bit more complicated.

Consider the following input file:

$ cat env.sh
#A=345
X=1
Y=2

Z=3
ABCD=/var/tmp
SSH_CONNECTION=192.168.31.1 21905 192.168.31.3 22
LAST_VAR='a
multi
line
value'

The simple sed no longer works for us:

$ sed 's/^/export /' env.sh
export #A=345                          # ??
export X=1
export Y=2
export                                 # ??
export Z=3
export ABCD=/var/tmp
export SSH_CONNECTION=192.168.31.1 21905 192.168.31.3 22
export LAST_VAR='a                     # ??
export multi                           # ??
export line                            # ??
export value'                          # ??

Another sed attempt that does a better job based on looking for lines of the format <variable_name>=:

$ sed -E 's/([^=#] =)/export \1/' env.sh
#export A=345
export X=1
export Y=2

export Z=3
export ABCD=/var/tmp
export SSH_CONNECTION=192.168.31.1 21905 192.168.31.3 22
export LAST_VAR='a
multi
line
value'

'course, this still falls short if there are more 'complex' entries in env.sh, eg:

$ cat env.sh
X=3
declare -n Y=X
MULTILINE='a
multi
x=345
line
value'

$ sed -E 's/([^=#] =)/export \1/' env.sh
export X=3
export declare -n Y=X                  # ??
export MULTILINE='a
multi
export x=345                           # ??
line
value'

At this point you would need to look at more robust parsing ideas ...

  •  Tags:  
  • bash
  • Related