Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sourcing env output

Tags:

linux

bash

shell

sh

I have some shell code I need to be debug, so I had the code dump its environment into a file

env > env.txt

and with my testing script I want to source it, test.sh:

. ./env.txt
echo $EXAMPLE
echo $EXAMPLE2

the contents of env.txt are:

EXAMPLE=sh /hello/command.sh
EXAMPLE2=/just/some/path

but, env does not put quotes around its values, which tends to cause a issue for $EXAMPLE, I get this error

test.sh: /hello/command.sh: not found

so clearly it is trying to run it instead of setting the variables.

what do you find is the quickest workaround for this problem?

like image 266
paxamus Avatar asked Mar 05 '13 22:03

paxamus


People also ask

How do I export a .ENV variable?

To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").

How do I print an environment variable in bash?

The “printenv” command displays the currently active environment variables and the previously specified environment variables in the shell. You can see the output of using the “printenv” command to display all the environment variables in the shell as per the snapshot below.

What are .ENV files?

The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.


3 Answers

Add the double quotes before redirecting the output to a file:

env | sed 's/=\(.*\)/="\1"/' > env.txt
like image 72
Ansgar Wiechers Avatar answered Sep 18 '22 15:09

Ansgar Wiechers


while read line; do
    declare "$line"
    # declare -x "$line"
    # export "$line"
done < env.txt

If you want to export the values to the environment, use the -x option to declare or use the export command instead.

like image 27
chepner Avatar answered Sep 17 '22 15:09

chepner


while read line; do
 var="${line%=*}"
 value="${line##*=}"
 eval "$var=\"$value\""
done <env.txt
like image 33
KarelSk Avatar answered Sep 18 '22 15:09

KarelSk