0

OK, so I've seen:

... which tells me that ampersand & is the separator for multiple commands running on a single line in a batch; and:

To set a numerical value to a variable, you may use the /a switch

Basically, I want to set up a counter variable, then increment it, then print it, then run some command in cmd.exe - so that each time I call the "previous line" command by using up key , I'd get a new counter value printed.

So this is my test:

C:\bin>set cnt=0

C:\bin>set /a cnt=%cnt%+1 & echo %cnt%
10

C:\bin>set /a cnt=%cnt%+1 & echo %cnt%
21

C:\bin>set /a cnt=%cnt%+1 & echo %cnt%
32

Of course, my final usage would be set /a cnt=%cnt%+1 & echo %cnt% & my_command.bat, but I dropped out my_command.bat from this discussion.

Anyways - what I thought would be increment by 1, turns out to be increment by 11 ?!

... Actually, I think I can tell what the problem is now: the set command also prints out the new value of the cnt variable! and then after it, the echo %cnt% prints the old value!

So, what would be the right syntax for a one liner, where set just sets but doesn't print; echo prints the updated value; and where I can append an arbitrary command (a batch file) at the end of the one-liner (besides the trivial "just use set and don't use echo"?)

sdbbs
  • 4,270
  • 5
  • 32
  • 87
  • 4
    `set /a` always prints the result, as long as it's executed directly on command line. You can redirect it to nirvana: `set /a cnt+=1 >nul`. To use the new value within the same line is [a bit more complicated](https://stackoverflow.com/questions/30282784/variables-are-not-behaving-as-expected/30284028#30284028). – Stephan Jul 29 '19 at 10:52
  • 3
    `set /A cnt=%cnt%+1` works, but `echo %cnt%` in the same line fails as it lacks [delayed expansion](https://ss64.com/nt/delayedexpansion.html); anyway, better use `set /A cnt=cnt+1` or even `set /A cnt+=1`; for echoing, either use delayed expansion like `echo !cnt!`, or use `call echo %%cnt%%` (in batch file) or `call echo %^cnt%` (in command prompt)... – aschipfl Jul 29 '19 at 10:52

0 Answers0