|
Answer» I need to do an If statement based on a variable being EQUAL to a string literal.
Here's my code:
SET MYNAME=%USERPROFILE%
IF %USERPROFILE%=="c:\documents and settings\XJHS037" (GOTO YES) ELSE (GOTO NO) ...
I'm sure the answer is simple but I can't get it to work. Can someone help?
Thanks
JeffIt is simple, like you thought. You need to remember to have quotes around the userprofile variable.
if "%userprofile%"=="c:\documents and settings\XJHS037"
One thing I am noticing, it looks like you are running on an XP machine. I didn't think that cmd prompt had the %userprofile% variable until Vista. I could be wrong though. Try doing an echo %userprofile% and see what you get.AWESOME! It worked! Thanks very much Raven. Yes I do have an XP but the userprofile variable does work. I'm very much a beginner and my FULL code was simple:
echo off
ECHO. ECHO. ECHO.
SET MYNAME=%USERPROFILE%
if /I "%USERPROFILE%"=="C:\documents and settings\XJHS037" (GOTO YES) ELSE (GOTO NO)
:YES ECHO %MYNAME% ECHO WAHOO! GOTO END
:NO ECHO %MYNAME% ECHO AWSHUCKS GOTO END
:END ECHO. ECHO. ECHO.
PAUSE
When I run the batch I do get "C:\documents and settings\XJHS037" from the echo
Thanks againA couple of points...
1. Some people think it is a good idea to get in the habit of always quoting variables in IF tests, because if one of the variables is empty (for example if the user just pressed ENTER in reponse to the SET /P in the following script) then without any quotes the script will crash with an error.
If you just press ENTER at the set /p prompt in this script it will crash with "echo was unexpected at this time." It won't get to the "echo finished" line.
Code: [Select]echo off set var1=cat set var2= set /p var2="Think of an animal: " if %var2%==%var1% echo Correct! echo finished
This one won't crash.
Code: [Select]echo off set var1=cat set var2= set /p var2="Think of an animal: " if "%var2%"=="%var1%" echo Correct! echo finished
2. They don't have to be quotes. They can be any characters that don't have a special meaning in batch, as long as they are the same both sides
e.g.
if (%var2%)==(%var1%) echo Correct! if [%var2%]==[%var1%] echo Correct! if {%var2%}=={%var1%} echo Correct! if ABC%var2%def==abc%var1%def echo Correct!
Quote from: Raven19528 on October 18, 2011, 12:41:10 PM I didn't think that cmd prompt had the %userprofile% variable until Vista.
%userprofile% was introduced in NT4.Thanks again to both of you! Trout - your suggestion makes sense and I've amended my script. GREAT Stuff!
|