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

发布于 2024-12-25 09:36:48 字数 214 浏览 3 评论 0原文

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

为了存储我正在做的变量:

echo %PATH% > dat

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

set PATH=???????

谢谢 拉米

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

for storing the variable i am doing:

echo %PATH% > dat

however, not sure how to load it later.

set PATH=???????

Thanks
Rami

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

淡淡绿茶香 2025-01-01 09:36:48

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

您必须注意 echo %PATH% > dat 在 %PATH% 值后插入一个额外的空格;如果稍后将附加路径添加到 PATH 变量,该空间可能会导致问题。只需通过以下方式消除多余的空间:echo %PATH%>数据

Just use: set /P PATH=< dat

You must note that echo %PATH% > dat insert 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.

酷遇一生 2025-01-01 09:36:48

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

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

setlocal enableDelayedExpansion
echo !path!>dat

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

set /p "PATH=" <dat

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

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

set /p "PATH=" <dat
雪若未夕 2025-01-01 09:36:48

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

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

和这个来写入文件,因为我遇到了空格问题

echo>dat %PATH%

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

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

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

echo>dat %PATH%
朮生 2025-01-01 09:36:48

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

echo "export PATH=$PATH" > dat

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

. ./dat

请注意,需要“获取”脚本(而不是仅执行它)才能修改当前的脚本环境——而不仅仅是新的儿童环境。

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

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.

甜警司 2025-01-01 09:36:48

即使路径值中包含空格和点,以下示例也能正常工作:

@REM Backup PATH variable value in a file
@REM Set PATHBACKUP variable with value in the file

@echo %PATH% > pathvalue.txt
@type pathvalue.txt
@for /f "delims=" %%l in (pathvalue.txt) do (
  @set line=%%l
)
@set PATHBACKUP=%line%
@echo %PATHBACKUP%

The following sample works even with spaces and dot in the path value:

@REM Backup PATH variable value in a file
@REM Set PATHBACKUP variable with value in the file

@echo %PATH% > pathvalue.txt
@type pathvalue.txt
@for /f "delims=" %%l in (pathvalue.txt) do (
  @set line=%%l
)
@set PATHBACKUP=%line%
@echo %PATHBACKUP%
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文