# Solved: Storing Environment variable to a text file



## Durant (Jun 21, 2009)

I'm having trouble writing a batch file that will run in the command line environment of Windows XP. I want to be able to set an environment variable - "set req_num=req#####" (where ##### is a 5 digit number) - and then store that value in a text file for later use after I reboot. Once I reboot and run the second half of my procedure, there will be no input from the user. So I need to be able to retrieve that environment variable value and re-assign it to an environment variable for use in another batch file. The value "req#####" represents a directory name. Here's what I've tried and here's why it doesn't work. 

For the batch file below, a text file named varname.txt has already been created, and it's contents are: set req_num=


rem Get Request ID value (which will represent a directory name)
rem Store the Request ID value in a text file for use after rebooting

:get_req_num
set req_num=

cls
echo.
echo Specify the Request ID Number as: req#####
echo.
set /p req_num=Please enter the Request ID: 
echo.

rem Make sure the value isn't empty
if (%req_num%)==() goto get_req_num

rem Check for a directory with that name, and if found, 
rem repeat until we get a unique directory name
if exist %systemdrive%\%req_num% ^&& goto get_req_num

echo You entered: %req_num%
echo.
pause

rem Build a batch file to re-set the environment variable
rem after our next reboot
rem Store variable into a text file named req_var.txt 

echo %req_num% > req_var.txt 

rem Combine varname.txt and req_var.txt together to make batch file
copy varname.txt+req_var.txt set_reqnum.bat >nul 


Now the problem comes when I try to store the environment variable into the text file named req_var.txt. The line "echo %req_num% > req_var.txt" seems to produce a space - or some other hidden character - at the end of the value. I don't know why, and I don't know how to get rid of it. If I call up req_var.txt in Notepad and hit the END key, I'm taken to the end, but the end includes a blank space after the value. After I reboot and run my next batch file, it's calls set_reqnum.bat to re-set the environment variable.

The batch file continues and executes this line:

if not exist %systemdrive%\%req_num%\backup md %systemdrive%\%req_num%\backup

But when expanded, the command looks like: C:\req00001 \backup (note the space after req00001) 

How do I get rid of this extra space, or is there a better way to capture this environment variable? Thanks!


----------



## Durant (Jun 21, 2009)

I finally found something that works. I added the following line:

set req_num=%req_num:~0,-2%


That chopped of the invisible codes at the end. I can't remember the codes, but probably a carriage return and a line feed.


----------



## TheOutcaste (Aug 8, 2007)

Welcome to TSG!

The space is because you've put one there:
* echo %req_num% > req_var.txt*
There is a space before the >, so it gets echoed as it's part of the Echo command.
Use this instead:
*Echo %req_num%>req_var.txt*
Or this
* >req_var.txt Echo %req_num%*
Just make sure there is no trailing space on the end of the line. I've been bitten by that a few times

And you can output the set command all in the same line:
* >set_reqnum.bat Echo Set reg_num=%req_num%*

HTH

Jerry


----------



## Durant (Jun 21, 2009)

You can tell I know little about batch files. I don't know how many hours I spent in frustration over this. And it was so simple. Thanks again for your help. I really appreciate it. That will never happen to me again.


----------



## Durant (Jun 21, 2009)

Well I still have the issue of the extra space at the end of the environment variable. It is occurring when I echo the variable contents to the text file - echo %req_num%>req_var.txt. Even though I closed the gap between the environment variable and the > sign. oh well, the bit of code I added - set req_num=%req_num:~0,-1% - fixes the issue. In my previous message I had used -2% instead of -1% and it worked then because I had been adding that extra space between the variable and the > sign, so there really were two things that needed to be removed. So I'm guessing there really is some sort of carriage return character getting inserted that manifests itself later as a space?!? Anyone kow the real answer to this?


----------



## Squashman (Apr 4, 2003)

Has nothing to do with Carriage Returns!
If there is any extraneous spaces in the line including at the end of the line it will get echoed to the text file.
If you use Notepad++ to edit your batch files you can turn on Show End of Line or Show all Charactars.


----------



## Durant (Jun 21, 2009)

All I know is that once I echo the variable to a file - after ensuring that there is no space at the end of the variable - when I pull up the file in Notepad and hit the END key to go to the end of the line, there is a space. And the space appears later when I insert that variable into a directory path, and my intended result is botched. Matter of fact, when I TRY to add a space at the end of my input, my batch file fails with an error. So it's not possible for me to add a space at the end without the batch file failing. See the following...

Contents of test2.cmd

cls
:get_req_num
set req_num=''
set /p req_num=Please enter the Request ID: 
if (%req_num%)==() goto get_req_num

The results when I intentionally add a space to the end of req00001


C:\test>set req_num=''

C:\test>set /p req_num=Please enter the Request ID:
Please enter the Request ID: req00001
)==() was unexpected at this time.

C:\test>if (req00001 )==() goto get_req_num

C:\test>


Upon viewing this output, I notice that the space I added is visible in the last echoed line: if (req00001 )

And if I run it again, and do not add the space, I get this...


C:\test>set req_num=''

C:\test>set /p req_num=Please enter the Request ID:
Please enter the Request ID: req00001

C:\test>if (req00001) == () goto get_req_num

C:\test>

Note that there is no space after req00001. 

I may investigate this further when I get time, but for now I'm happy that I have a way around it, even if I do not understand how it's happening.


----------



## TheOutcaste (Aug 8, 2007)

You can avoid the error when you enter a trailing space by using quotes instead of parentheses:
* if "%req_num%"=="" goto get_req_num*

I don't know where the space (or whatever the character is) is coming from. I don't get a space on the end unless I actually type one when entering the info at the prompt, or if I add a space after %reg_num% on the line that echoes it to a file, so I haven't a clue why it's happening for you. At least you've got a fix for it. But if whatever is adding it gets corrected at some point, the fix will start chopping the last character off of whatever gets entered.

You can add some test lines to see where that space is creeping in at. Just add the following in several places after you input the value, and again just before echoing it to the file:
* Echo =%req_num%=*
Your test shows it's not there right after it's entered, so it's getting added someplace after that.
If the file you run after rebooting constructs a variable to use in the If statement, that could be the culprit.
for example

```
call set_regnum.bat
Set Fold=%systemdrive%\%req_num%
If Not Exist %Fold%\backup md %Fold%\backup
```
If there is a space at the end of the *Set Fold* line it will get added, so the if statement will expand to
c:\req0001 \backup

One of those little glitches that can be a real pain to track down.


----------



## Squashman (Apr 4, 2003)

Post all your batch files here as text files and we can look at it for you.


----------



## Squashman (Apr 4, 2003)

TheOutcaste said:


> I don't know where the space (or whatever the character is) is coming from. I don't get a space on the end unless I actually type one when entering the info at the prompt, or if I add a space after %reg_num% on the line that echoes it to a file, so I haven't a clue why it's happening for you. At least you've got a fix for it. But if whatever is adding it gets corrected at some point, the fix will start chopping the last character off of whatever gets entered.


Jerry makes a good point here. If you truly want to make sure your variables have the spaces trimmed from the beginning and end you either have to code correctly or use a sub routine to trim the spaces from your variables. There are lots of examples on the web to do this correctly. The way you are doing it could cause data to be truncated.

Here is one example you could use to trip white space.
http://cypressor.twoday.net/stories/4496343/


----------



## Durant (Jun 21, 2009)

OK - It's happening early on, so I'm not going to upload the whole shebang. I've included some modified code to show what's going on. 
I've added a routine to display the character count of an environment variable and display it. 

To properly execute the bach file, a text file named varname.txt must already exist and I created it this way...

copy con varname.txt
set req_num=^Z (press ENTER)

The ^Z occurs when I press the F6 key. I then pressed ENTER to save the file. If you look at the start of the main batch file, I was going to include the code to delete varname.txt and recreate it by adding the following line...

echo set req_num=>varname.txt

I ended up remming it out because (and this may somehow tie into the issue) if I create it this way, when the main batch file builds the set_reqnum.cmd batch file, I end up with two lines like so...

C:\test>type set_reqnum.cmd
set req_num=
req00001

It should be: set req_num.cmd=req00001 (no space at the end )

The character counting routine shows that %req_num% has a length of 8, which is correct if you enter req00001 (no space) as the input. Once the batch file is finished, if I call up req_var.txt into Notepad and hit the END key, the cursor is right next to the last character of the string - there is no space. So it does not appear to be occurring during when the following line is executed...

echo %req_num%>req_var.txt

I can't reconcile the fact that echoing to varname.txt (example above) seems to produce a carriage return, yet echoing %req_num%>req_var.txt does not... unless the character counting routine does not count carriage returns as a character. I frankly don't understand how the character counting routine does what it does. 

Notice that in the main batch file I've added a line which calls the batch file that was built (named set_reqnum.cmd) and this line is remmed out initially.

rem call set_reqnum.cmd

If you remove the "rem" and save the batch file (I call it test.cmd) and then run it again, you will see the length of the string variable is now 9. So something seems to be happening when it builds set_reqnum.cmd
It's either then or during the echo %req_num%>req_var.txt

Anyway... I'm confused... maybe I should take up drinking... 
By the way, thanks for everyones help! 


@echo off
del req_var.txt >nul
del set_reqnum.cmd>nul
rem del varname.txt>nul
rem echo set req_num=>varname.txt

:start

cls
:get_req_num
set req_num=''
cls
echo Don't forget to create varname.txt before hand
echo copy con varname.txt
echo set req_num=
echo Then press F6 and the ENTER
echo. 
echo Specify the Request ID Number as: req#####
echo.
set /p req_num=Please enter the Request ID:
if (%req_num%)==() goto get_req_num
echo.
echo You entered: %req_num%
echo.
echo %req_num%>req_var.txt
pause
copy varname.txt+req_var.txt set_reqnum.cmd>nul


rem Modified Routine to show the length of the string variable
rem Un-rem the next line to see the change in length of req_num
rem call set_reqnum.cmd

echo.
@echo off & setlocal enableextensions
set testString_=%req_num%
call :GetLength "%testString_%" length_
rem echo 123456789 123456789 123456789
echo.%testString_%
echo.
echo Length = %length_%
goto :EOF
endlocal & goto :EOF
::
::===============================================================
:: Subroutine: Return the length of a string
:GetLength string count
setlocal enableextensions enabledelayedexpansion
if "%~1"=="" (endlocal & set "%2=0" & goto :EOF)
set s=%~1
for /L %%c in (0,1,255) do (
set si=!s:~%%c,1!
if defined si set charCount=%%c
)
set /a charCount+=1
endlocal & set "%2=%charCount%" & goto :EOF


----------



## Durant (Jun 21, 2009)

I checked the contents of set_reqnum.cmd with Notepad after running the main batch file and pressed the END key again and the cursor went just to the right of the last character with no space between them. I also noticed that at the very beginning of the next line was a small arrow (pointing to the right). I tried to copy that here (see below) but the arrow gets re-interpreted to whatever that is that's showing. What is that? A carriage return?

set req_num=req00001


The other thing, which probably doesn't matter, I'm running Vista 64.


----------



## TheOutcaste (Aug 8, 2007)

Well, you won't want to hear this, but I copied the above into notepad++, saved it, and created the varnum.txt file.
I enter req00001 and is shows a length of 8
I remove the rem so it calls the created batch file, and it still shows 8. I don't get the extra space. This is on XP.

I wouldn't use the varnum.txt or req_num.txt files, just output the line all at once:
* Echo set req_num=%req_num%>set_reqnum.cmd*
This will avoid the EOF character being added to the file by the Copy command


Durant said:


> I checked the contents of set_reqnum.cmd with Notepad after running the main batch file and pressed the END key again and the cursor went just to the right of the last character with no space between them.


 So the variable doesn't have a space at the end.



Durant said:


> I also noticed that at the very beginning of the next line was a small arrow (pointing to the right). I tried to copy that here (see below) but the arrow gets re-interpreted to whatever that is that's showing. What is that? A carriage return?
> 
> set req_num=req00001
> 
> ...


The symbol you see in notepad is the CTRL+Z End of File (EOF) character that you entered using the F6 key. The Copy command also adds a CTRL+Z character to the end of the file. Also known as the SUB control character (notepad++ will show it that way). It's on a separate line, so shouldn't affect the req_num variable

I wouldn't think Vista x64 would make a difference, but it may be that CTRL+Z that appears as a "space". I'll give that a try in a few minutes. If that is the problem, creating the file directly with just the one echo statement should take care of it.


----------



## TheOutcaste (Aug 8, 2007)

I get 8 characters for the length on Vista Home Premium x64, no extra space on the end.


----------



## Durant (Jun 21, 2009)

That beats all! Although I've been around PC's long enough to have seen lots of weird stuff - or rather, stuff I didn't understand. So you got 8 characters each time, even when using Vista 64? Wow! I dunno but taking up drinking is getting more appealing. I will try the line of code you suggested! Many thanks!


----------



## Squashman (Apr 4, 2003)

I try to have a glass of Makers Mark at least a couple of times a week. On the rocks!


----------



## Durant (Jun 21, 2009)

I made the change you suggested and it works fine! As to the case of the missing space, I'm OK with forgetting it and moving on. Thanks for all the help!

Cheers! :up:


----------

