Home > front end >  CMD Script - cannot set variable within FIND
CMD Script - cannot set variable within FIND

Time:05-01

  1. I use an external program to generate a string
  2. I need to find out if the string has the word "not" in it
  3. If so, I set a certain variable to use later.

1 and 2 work without problems, but I cannot get 3 to work.

My code:

SET EXE="path\to\program.exe"

for /f "delims=" %%i in ('%EXE% argument') do (
rem echo %%i
set mystatus=%%i
)

echo %mystatus%

^ works up to here ^ - echo returns the correct value. Now I want to return a simpler value that tells me if the string "not" was present in %mystatus% var

set "isNot="

ECHO.%mystatus%| FIND /I "not">Nul && ( 
  Echo.Found "not"
  do something
  rem ^this works^
  set isNot= "true"
) || (
  Echo.Did not find "not"
  do something
  rem ^this works^
  set isNot= "false"
)

now, out of FIND, this returns nothing: WHY?

echo %isNot%

CodePudding user response:

Idiotic mistake, it seems. There should not be spaces after = when setting a variable. Removed the spaces, and it work as it should.

CodePudding user response:

I find your answer - let's say, naïve.

First, I can't reproduce your result. It worked perfectly for me, returning isnot set to Space"false" or Space"true", not nothing.

Had isnot been undefined, then the echo response should have been Echo is off, so isnot was defined in your test. I would use echo %isNot% for this test so that the string is shown with an obvious delimiter. If it contained just spaces - well, they tend to be remarkably invisible.

As to the solution, I's suggest

set "isnot="
if "%mystatus" neq "%mystatus:not=%" set "isnot=Y"

which avoids find and piping and conditions, setting isnot to be either defined or not defined as appropriate, ready for testing using

if defined isnot (echo not was not found) else (echo not was found)

The reason for this is that if defined works on the run-time status of the variable, hence it can be used within a code block where the variable may be switched from one status to the other.

Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign a terminal \, Space or " - build pathnames from the elements - counterintuitively, it is likely to make the process easier.

  • Related