Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly perform modulus operations in Batch?

I'm trying to write a batch file that performs operations depending on the result of a modulus operation performed on a set variable. However, I can't seem to get it quite right.

To first of all test my syntax for the mathematical operation, I've been trying to get a simpler script to produce desired results.

:START
SETLOCAL
SET /P Input-Num="Input Number: "
SET /A Input-Num=%Input-Num% %% 2
ECHO %Input-Num%
ENDLOCAL
PAUSE 
:END

If I input 5, the expected output is 1. However, instead I get a message saying Missing operator. and then it outputs 5.

What am I doing wrong here?

like image 576
Iszi Avatar asked Jul 17 '12 18:07

Iszi


People also ask

What is %% A?

%%a are special variables created by the for command to represent the current loop item or a token of a current line. for is probably about the most complicated and powerful part of batch files. If you need loop, then in most cases for has you covered.

What is Usebackq in batch script?

usebackq. Specifies to run a back-quoted string as a command, use a single-quoted string as a literal string, or, for long file names that contain spaces, allow file names in <set> , to each be enclosed in double-quotation marks.

What is batch file example?

A batch file is simply a text file saved with the .bat file extension. It can be written using Notepad or any other text editor. A simple batch file will be: // When echo is turned off, the command prompt doesn't appear in the Command Prompt window. ECHO OFF // The following command writes GeeksforGeeks to the console.

How do you write a batch file in a script?

To create a Windows batch file, follow these steps: Open a text file, such as a Notepad or WordPad document. Add your commands, starting with @echo [off], followed by, each in a new line, title [title of your batch script], echo [first line], and pause. Save your file with the file extension BAT, for example, test.


1 Answers

Using SET /P is your problem, as 5 is no longer treated as a numerical value. Your example as above works as expected

like image 80
LittleBobbyTables - Au Revoir Avatar answered Sep 21 '22 12:09

LittleBobbyTables - Au Revoir