如果在.bat文件中

时间:2015-09-24 16:27:35

标签: windows batch-file cmd

@echo off
if "%1"=="" (
:WriteAgain
set x= 
set /p variables=Write your expression 
if "%variables%"=="help" (
echo Use arithmetical operations and numbers without spaces. + for sum, * for multiplication, / for 

devision, - for subtraction 
exit
) else (
set variables=%variables: =%
set /a x=%Variables% 2>Error.txt
if %errorlevel% neq 0 goto ErrorOccured
echo %x% 
pause
exit
)
:ErrorOccured
echo Your expression is not valid 
goto WriteAgain
) else (
set variables=%*
set variables=%variables: =%
set /a x=%variables% 2>Error.txt
if %errorlevel% neq 0 goto ErrorOccured
echo %x%
)

问候,这是一个简单的计算。它可以直接从cmd使用,但首先if也无法正常工作

) else (
set variables=%variables: =%
set /a x=%Variables% 2>Error.txt
if %errorlevel% neq 0 goto ErrorOccured
echo %x%

始终ErrorOccured。我没有看到任何问题,而且没有首先if

2 个答案:

答案 0 :(得分:1)

也许下一个代码可以提供帮助。请注意EnableDelayedExpansion和正确引用,以允许在set /?中看到所有算术运算。

@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
if "%~1"=="" goto NeedHelp
set "variables=%*"

:CommonCalc
if "%variables%"=="" goto ErrorOccured
rem spaces do not matter set "variables=!variables: =!"
set /a "x=!variables!" 2>Error.txt
if %errorlevel% neq 0 goto ErrorOccured
echo !variables!=%x%
exit /B

:WriteAgain
set "x="
set "variables="
set /p "variables=Write your expression: "
if /I "!variables!"=="" goto NeedHelp 
goto CommonCalc

:NeedHelp
echo Use arithmetical operations and numbers without spaces. 
echo + for sum, * for multiplication, / for division, - for subtraction
echo %% for modulus ^(remainder after division^)
goto WriteAgain

:ErrorOccured
echo Your "!variables!" expression is not valid ^(%errorlevel%^)
rem next line: clear errorlevel to 0
(call )
goto NeedHelp

但是,proper escaping如果用作批处理行参数,则某些运算符需要。例如:

  • 否定32766441.bat ^^^!0返回!0=1
  • 逻辑 32766441.bat 6^|9返回6|9=15
  • left shift 32766441.bat 5^<^<3返回5<<3=40等。

(call )凭借this dbenham's answer

清除errorlevel的技巧

答案 1 :(得分:0)

我不知道它是否符合您的期望,我无法运行ErrorOccured标签。

@echo off
cls
set x= 

:WriteAgain
if "%1"=="" (
    set /p "variables=Write your expression " || cls &goto help
    ) else (
    set "variables=%*"
)

set variables=%variables: =%
set /a x=%variables% 2>Error.txt
:: if %errorlevel% neq 0 goto ErrorOccured
if not ERRORLEVEL 0 goto ErrorOccured
call :result %variables% %x%
exit /b 0

:help
echo(
echo Use arithmetical operations and numbers without spaces.
echo + for sum, * for multiplication, / for devision, - for subtraction
goto WriteAgain

:result
echo formula is %~1 and the result is %~2
goto:EOF

:ErrorOccured
cls
echo(
echo Your expression is not valid 
goto :help

exit /b 0

这必须得到优化。