Thursday, June 28, 2007

Setting Variable Value From File

Let's say you have file containing some string, and you want to get that string and assign it to an environment variable.

echo Hello World > foo.txt

There are two ways you can assign the content of that file to an environment variable.  One is to use redirection.  To do this, you need to make the set command interactive by using the /P switch.

set /P BAR=<foo.txt

echo %BAR%

If you have more than one lines in the file, this will set the variable value to the first line in the file.

The other method is using the for loop, telling it to read from the file.

for /F "tokens=*" %x in (foo.txt) do (

  set BAR=%x


The "tokens=*" option tells it to consume the whole line, so that if you have any white spaces in the line, it will not pick up the first word only.  If you use this approach and there are more than one lines in your file, your variable will end up with the last line as its value.

1 comment:

Archaeoprophet said...

Cool, I had made a password application that way where the office manager was able to change the passcode as often as he wished. I was awarded the ability to get several girls pregnant later on...ha ha...just kidding.