3

What is wrong with the following command lines for my batch script?

set test=BE99012345678901


if %test% == "BE99????????????"(
echo This number begins with BE99
)
Else (
echo This number doesn't begin with BE99
)
pause

3 Answers 3

2

Try this:

set test=BE99012345678901

if "%test:~0,4%"=="BE99" (
echo This number begins with BE99
) else (
echo This number doesn't begin with BE99
)
pause

You will get following output:

This number begins with BE99

Kindly note:

if %test% == "BE99????????????" will do this: "BE99012345678901" == "BE99????????????"

and this will show following output:

This number doesn't begin with BE99

2
  • isn't %test% only a cmd/DOS syntax, no valid in *nix, whereas what you have written is bash, so $test would be the thing to use in the if in your case. Though he did specify batch(so, cmd no doubt).
    – barlop
    Jun 19, 2014 at 18:58
  • Barlop you are correct, thanks for mentioning that. I have made changes in my answer.
    – ani627
    Jun 20, 2014 at 6:45
2

barlop's answer covers most of your problems. It should also be noted that you need the ELSE to be on the same line as the closing parenthesis for the IF. Like so:

IF "%var%"=="whatever" (
  REM Do stuff
) ELSE (
  REM Do other stuff
)
0

It looks like you can't use question mark or any wildcard in that a==b line The == operator doesn't take ? as special, it takes it as literal. And it doesn't look at filenames either. So, that just goes to prove it really does just take ? as literal.

Also, in Linux if you did echo ? it would be interpreted by the shell before it goes to the echo command and it would return a filename of one char length. In Windows ? or * are not interpreted by the shell, they are passed to a command. DIR uses ? and *, treats them as special, ECHO doesn't, and the test for equality if == doesn't, and it would just echo a question mark. I doubt what you wrote there would be valid in bash either. As in linux ? and * are always to do with filenames and you seem to want purely for the variable comparison.

C:\a>touch BE99 <---- a gnuwin32 touch line to create a file called BE99

C:\a>if BE99==BE9? echo true

C:\a>if "BE99"=="BE9?" echo true

C:\a>

C:\a>dir BE9? /b
BE99

C:\a>

So, ? works with DIR, but not with a==b

But besides that, if you do "4"==4 then it will say false, as you have to do quotes around both or around neither. The reason for quotes is if you do %var%==%var% and %var% is empty then you have a syntax error because it works by substitution, substitution so you get nothing on either side of the == so just if ==. So better to use quotes, than no quotes. Some use []. if [%var%]==[%var%]

You can use this

C:\a>set test=BE9923432423

C:\a>echo %test:~0,4%
BE99

So, in your code you could do if "%test:~0,4%"=="BE99" (

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.