Strange behavior in Batch script

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Grapefruits
Posts: 7
Joined: 27 May 2018 11:43

Strange behavior in Batch script

#1 Post by Grapefruits » 31 Jul 2018 15:09

So I have this script. It's supposed to check if the input (%skiller%) is in the variable %tree%. So if I input Sword, it'll look for the string "Sword" in the variable %tree%. The tree value is "Sword Shield". Afterward, it checks the variable %skillsunlocked% to see if it has the input. If it has the input, it'll say "You already unlocked it!". Strange thing is, when I input "Sword" it always says "You already unlocked Sword", even though %skillsunlocked% has no value. If I input "Mace", which isn't in the %tree% variable, it goes back to :FUNC, which is the intended behaviour. But when I input "Sword", it always says I unlocked Sword, even though %skillunlocked% does not contain Sword.

Code: Select all

:FUNC
set skillsunlocked="
set "tree=Sword Shield"
set /p skiller="Enter skill..."
echo.%tree% | findstr /C:"%skiller%" 1>nul
if "%errorlevel%" == "0" (
      echo.%skillsunlocked% | findstr /C:"%skiller%" 1>nul
      if "%errorlevel%" == "0" (
            echo You already unlocked %skiller%^^!
            pause
            GOTO :FUNC
      )
) else (
     GOTO :FUNC
)
I thought maybe a blank variable was throwing it off, so I tried adding skillsunlocked=None, but it still behaved the same. The first findstr works, while the second one doesn't. Any hints or thoughts? :?

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Strange behavior in Batch script

#2 Post by Squashman » 31 Jul 2018 15:16

Delayed Expansion!

Code: Select all

:FUNC
set skillsunlocked="
set "tree=Sword Shield"
set /p skiller="Enter skill..."
echo.%tree% | findstr /C:"%skiller%" 1>nul
if "%errorlevel%" == "0" (
      echo.%skillsunlocked% | findstr /C:"%skiller%" 1>nul
     setlocal enabledelayedexpansion
      if "!errorlevel!" == "0" (
            echo You already unlocked %skiller%^^!
            pause
            GOTO :FUNC
      )
     endlocal
) else (
     GOTO :FUNC
)

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Strange behavior in Batch script

#3 Post by aGerman » 31 Jul 2018 15:22

You try to access the %errorlevel% variable in a parenthesized block of command lines. You can't get its changed value without delayed expansion and !! instead of %%. Another problem is the space between the variable and the | operator. The space belongs to the ECHOed string and may falsify your result.
But I wouldn't even use the external FINDSTR tool. What about string replacement? If "!tree:%skiller%=!" is still the same as "!tree!" then tree doesn't contain skiller.

Steffen

Post Reply