In the post, we will see how to get input from user in windows batch scripting and do arithmetic operation.
The SET statement provides /P switch which is used to get input on prompt.
Look at the following script to see how user is prompted to input two numbers.
The sum result is displayed thereafter.
@echo off
SET /P x=Enter value of x:
SET /P y=Enter value of y:
set /A z=%x%+%y%
echo The sum of x=%x% and y=%y% is %z%
pause
Tips:
- Give extra space after colon(:)
- The /A switch is used to write arithmetic expression. When /A is followed by expression then that expression is evaluated as arithmetic operation. Look at the following script in this regard:
@echo off
set i=1
for %%f in (*) do (
@echo %i% %%~nf
set /a i+=1
)
endlocal
@pause
NOTE:
- The += is a compound operator used in i+=1 which is an arithmetic expression. Since variable is reinitialized in each iteration, simple SET statement will not be enough. We use /A switch to imply that i+=1 is an arithmetic expression.
- Here, wildcard (*) and (*.*) have subtle difference. The *.* implies to loop through all files and folders which contain a period symbol in their names. But * is just any file or folder.
No comments:
Post a Comment