Search code examples
batch-filecoding-stylesetquotes

Batch File Techinque for Set /A and quoting


I've always wondered about how and when to use quotes if my script is making a calculation. For example,

Set /A exp=%some%+(!calculation!-0).

I know, if the line uses parentheses, and I'm inside an IF block, I should use

Set /A exp="%some%+(!calculation!-0)".

The quotes just go around the part after the equals.

Aside from that, quoting from the variable name to the end of the line,

Set /A "exp=%some%+(!calculation!-0)"

seems to work as well.

I'm wondering, is there a "proper" way to use SET /A? What's the correct/best technique for batch scripts? When should I use quotes? Are they mostly optional unless one gets an error?

Thank you.


Solution

  • It makes more sense, if you try it without /a: if you use "after the =, it will become part of the variable; if you use it before =, it delimits the expression (usualy used to avoid unintended or insert intended trailing spaces in a variable)

    C:\>set x="1+3"
    C:\>set x
    x="1+3"
    
    C:\>set "x=2+5"
    C:\>set x
    x=2+5
    
    C:\>set x=text  
    C:\>echo -%x%-
    -text  -
    
    C:\>set "x=text"  
    C:\>echo -%x%-
    -text-
    

    (note, there are two "unintended" spaces after set x=text and set "x=text")

    with /a, the qoutes are just stripped (/a was added to the former setcommand from "good old DOS")