开发者

Writing a simple bat file?

I am writing a simple batch file and i get this "The syntax of the command is incorrect" error for the if statement.The batch file is as below:

@echo off

set ARCH=%PROCESSOR_ARCHITECTURE%

if %ARCH% == 'x86'
(
)

I also tried

if %ARCH% EQU 'x86'

What is w开发者_运维百科rong with the if statement?


try

@echo off
set ARCH=%PROCESSOR_ARCHITECTURE%
if %ARCH% == x86 ( echo ok )
rem or %ARCH% EQU x86

and while you are at it, why not learn vbscript as well, here's the equivalent

Set WshShell = WScript.CreateObject("WScript.Shell")
Set Wsharch = WshShell.Environment("SYSTEM")
arch=Wsharch.Item("PROCESSOR_ARCHITECTURE")
If arch = "x86" Then
    WScript.Echo "PROCESSOR_ARCHITECTURE is x86"
End If
' if Instr(arch,"86") > 0 then


ETA:

Actually i want to check if the architecture contains string 64. Something like:

if %ARCH% == '*64*' ( echo ok )

How can i do that?

For this you can employ the help of a nice little tool called findstr which searches for patterns in files or command output. Just pipe the value of the variable into findstr:

echo %ARCH% | findstr 64

which will find any line in the output that contains 64 somewhere. In this case, there is only one line but that's fine.

However, this also causes the line to be output on screen, so change it into the following:

echo %ARCH% | findstr 64 > nul 2>&1

which will redirect any output (including error messages) into nothingness.

Now, findstr sets a special value (the exit code, or error level) depending on whether the string was found or not. You can use that to test whether 64 in fact appeared in the output:

echo %ARCH% | findstr 64 > nul 2>&1
if errorlevel 1 (
    echo 64 did NOT appear (error level greater 0 usually means failure)
) else (
    echo 64 DID appear
)

To your original question:

The opening parenthesis must occur on the same line as the if statement itself:

@echo off 
 
set ARCH=%PROCESSOR_ARCHITECTURE% 
 
if %ARCH% == x86 ( 
    rem ...
) 

does work.

Remember that cmd's parser is line-based; therefore caution is advised with anything that needs to span multiple lines. Another option would be to escape the line break:

@echo off 
 
set ARCH=%PROCESSOR_ARCHITECTURE% 
 
if %ARCH% == x86 ^
( 
    rem ...
)

The ^ is the escape character in cmd and in this use it's effectively a line-continuation operator so the parser accepts the opening parenthesis on the next line as part of the current statement (which usually would be terminated by a line break).

And yes, the use of single quotes for the literal string value in the comparison will get you into other problems as Carlos Gutiérrez noted, since essentially everything in cmd is a string literal. So you would be comparing with the literal string

'x86'

instead of

x86

what is actually contained in the environment variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜