sramij
sramij

Reputation: 4925

how to set environment variable from file contents?

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

Upvotes: 17

Views: 41535

Answers (5)

efdummy
efdummy

Reputation: 704

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%

Upvotes: 0

SpacedMonkey
SpacedMonkey

Reputation: 2783

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%

Upvotes: 5

Aacini
Aacini

Reputation: 67296

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.

Upvotes: 17

dbenham
dbenham

Reputation: 130929

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

Upvotes: 6

ziesemer
ziesemer

Reputation: 28707

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.

Upvotes: 3

Related Questions