Bug in CMD.exe? Parentheses confused

R

Rich Pasco

Scripts for the command-shell interpreter cmd.exe use parentheses in
two ways: One is for blocks, as in

if condition (
do this
and this
)

The other is for grouping in arithmetic expressions, like this:

set /a result = 2*(3+4)

which assigns the value 14 to the environment variable "result."

However, using such an assignment inside a block leads to confusion, e.g.

if 1==1 (
set /a result = 2*(3+4)
)

which leads to an "Unbalanced parenthesis" error as the closing
parenthesis on the arithmetic expression is mistaken as the closing
parenthesis on the conditional block.

- Rich
 
E

Eman

Rich said:
However, using such an assignment inside a block leads to
confusion, e.g.

if 1==1 (
set /a result = 2*(3+4)
)

which leads to an "Unbalanced parenthesis" error as the
closing parenthesis on the arithmetic expression is
mistaken as the closing parenthesis on the conditional
block.

It's not out of place to escape all suspect
on the right of the "set something=" statement.
E.g., this would work:

~~
@echo off
if 1==1 (
set /a result = 2*^(3+4^)
)
echo result=%result%
~~

And this one too:

~~
@echo off
if 1==1 (
set /a result =^ ^2^*^(^3^+^4^)
)
echo result=%result%
~~
 
R

Rich Pasco

Thanks.

Also you the numbers in set statement arithmetic must be interger, not
decimal fractions.

This works:
set /a sum=2+2

This doesn't:
set /a sum=2.1+2.2

- Rich
 
M

Matthias Tacke

Rich said:
Scripts for the command-shell interpreter cmd.exe use parentheses in
two ways: One is for blocks, as in

if condition (
do this
and this
)

The other is for grouping in arithmetic expressions, like this:

set /a result = 2*(3+4)

which assigns the value 14 to the environment variable "result."

However, using such an assignment inside a block leads to confusion, e.g.

if 1==1 (
set /a result = 2*(3+4)
)

My german help of "set /?" says you've to put the expression in dbl quotes
when using arithmetic operators. Even it isn't necessary in most cases,
you've to use them for this to work.

if 1==1 (
set /a result ="2*(3+4)"
)
 
R

Rich Pasco

Danke sehr, Matthais. Now that you mention it, the English help file
also says,

If you use any of the logical or modulus operators, you will need to
enclose the expression string in quotes.

I hadn't noticed that before. While Eman's suggestion of escaping the
special characters works, putting quotes around the entire expression
is simpler and makes it easier to read.

Since that is documented in the help file, I withdraw my "bug" report. :)

- Rich
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top