sourcing env output

泪湿孤枕 提交于 2019-12-01 03:57:09

问题


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?


回答1:


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.




回答2:


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

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



回答3:


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


来源:https://stackoverflow.com/questions/15235729/sourcing-env-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!