windows 如何从文件内容设置环境变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8767017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 09:05:31  来源:igfitidea点击:

how to set environment variable from file contents?

windowsshellbatch-filecygwinwindows-shell

提问by sramij

On windows/cygwin, i want to be able save the PATH variable to file on one machine and load it onto the other machine;

在 windows/cygwin 上,我希望能够将 PATH 变量保存到一台机器上的文件并将其加载到另一台机器上;

for storing the variable i am doing:

用于存储我正在做的变量:

echo %PATH% > dat

however, not sure how to load it later.

但是,不确定以后如何加载它。

set PATH=???????

Thanks Rami

谢谢拉米

回答by Aacini

Just use: set /P PATH=< dat

只需使用: set /P PATH=< dat

You must note that echo %PATH% > datinsert an additional space after %PATH% value; that space may cause problems if an additional path is later added to PATH variable. Just eliminate the extra space this way: echo %PATH%> dat.

您必须注意echo %PATH% > dat在 %PATH% 值后插入一个额外的空格;如果稍后将附加路径添加到 PATH 变量,则该空间可能会导致问题。只要消除了额外的空间是这样的:echo %PATH%> dat

回答by dbenham

echo %PATH%will fail if the PATH contains an unquoted & or ^ (this is not likely, but certainly possible)

echo %PATH%如果 PATH 包含未加引号的 & 或 ^(这不太可能,但肯定可能),则会失败

A more reliable solution is to use:

更可靠的解决方案是使用:

setlocal enableDelayedExpansion
echo !path!>dat

Then you can use Aacini's suggested method of reading the value back in

然后您可以使用 Aacini 建议的方法读取值

set /p "PATH=" <dat

回答by ziesemer

Being dependent upon Cygwin, how how about putting the command in your saved file, e.g.:

依赖于 Cygwin,如何将命令放入您保存的文件中,例如:

echo "export PATH=$PATH" > dat

Then sourcing the script later to set the path:

然后稍后获取脚本以设置路径:

. ./dat

Note that "sourcing" the script (vs. just executing it) is required for it to modify your current environment - and not just new child environments.

请注意,它需要“采购”脚本(而不是仅执行它)来修改您当前的环境 - 而不仅仅是新的子环境。

回答by SpacedMonkey

This might be evil but on Windows I am using this:

这可能是邪恶的,但在 Windows 上我正在使用它:

for /F %%g in (dat) do set PATH=%%g

and this to write the file because I had trouble with spaces

这是为了写文件,因为我有空格问题

echo>dat %PATH%