Reputation: 148
I am basically a Linux guy forced into a Windows world lately, so I need to write a bat script, but I ran into the following problem.
Here is my .bat script
///////////////////////////
echo.
echo This is testbat script
echo -----------------------------------------------------------
echo.
if "%1"=="" (
echo "You did not enter an argument
) else (
set "myvar="
echo Argument is %1%
set myvar=%1%
if "%myvar%"=="%1%" (
echo myvar is %myvar%
) else (
echo myvar is not set to %1
)
)
////////////////////////////////////////////////////////
It seems that I need to run this script twice to get myvar to change.
For example, FIRST RUN:
testbat.bat hello
OUTPUT:
This is testbat script
-----------------------
Argument is hello
myvar is not set to hello
SECOND RUN:
testbat.bat hello
OUTPUT:
This is testbat script
-----------------------
Argument is hello
myvar is hello
NOW CHANGE the argument to bye THIRD RUN:
testbat.bat bye
OUTPUT: This is testbat script -----------------------
Argument is bye
myvar is not set to bye (In fact, it is still hello here)
FOURTH RUN (same input as THIRD):
> testbat.bat bye
OUTPUT: This is testbat script -----------------------
Argument is bye
myvar is bye (Finally gets updated)
////////////////////////////////////
My question is why the script doesn't update the environment variable the first time?
Why do I need to run the script a second time to get the variable to change to the new value in the script? I used the SET command and discovered that the value is changed in the environment, why does the script output reflect the old value. Of course, the value in the environment might not change until after the script completed, not sure.
I'm running the script and then using the up arrow to edit the command line if that makes any difference, it doesn't seem to though.
Upvotes: 0
Views: 90
Reputation: 41234
You cannot use %1%
as an environment variable because %1
is a command line replaceable parameter.
To set/change
and display
a variable within parentheses or a loop you need
@echo off
setlocal enabledelayedexpansion
and use echo !myvar!
Upvotes: 1