paxamus
paxamus

Reputation: 127

sourcing env output

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?

Upvotes: 7

Views: 3660

Answers (4)

Mat M
Mat M

Reputation: 1904

Unless you need the _ variable, export shows all variables, and quote the ones that need it.

Note: export is a shell built-in and output differs depending on the shell/

$>printenv | grep "^LD_LIBRARY_PATH"
LD_LIBRARY_PATH=
$>env | grep "^LD_LIBRARY_PATH"
LD_LIBRARY_PATH=
# ksh & zsh
$>export -p | grep "^LD_LIBRARY_PATH"
LD_LIBRARY_PATH=''
# bash ; remove declare -x
$>export -p | cut -d" " -f3- | grep "^LD_LIBRARY_PATH"
LD_LIBRARY_PATH=''
# dash ; remove export
$>export -p | cut -d" " -f2- | grep "^LD_LIBRARY_PATH"
LD_LIBRARY_PATH=''

See manpages of your shell.

Upvotes: 2

chepner
chepner

Reputation: 532538

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.

Upvotes: 7

KarelSk
KarelSk

Reputation: 605

while read line; do
 var="${line%=*}"
 value="${line##*=}"
 eval "$var=\"$value\""
done <env.txt

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200573

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

env | sed 's/=\(.*\)/="\1"/' > env.txt

Upvotes: 13

Related Questions