1

When using the SET command in command prompt, what does % and ! mean, for example

set VAR=before
if "%VAR%" == "before" (
set VAR=after
if "!VAR!" == "after" @echo If you see this, it worked)
set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%

Notice how there's %i and !VAR! what does this mean, %i cant be a variable right? as variables are written out like %variable%.

Any ideas what these are?. Also is the (*) just a literal?

Regards, S

1 Answers1

0

In normal cases you can access variable value by enclosing its name with % :

set var=a
echo %var%

As when there is composition of commands with & or a few commands are put in brackets the set will take effect after all of them are executed.Then you need delayed expansion to access your variable and to enclose it with !

setlocal enableDelayedExpansion
if exist c:\ (
  set var2=a
  echo !var2!

)

Take a more close look at SET command.

in for loops you have a special variables that works only in context of for command - a tokens that change its values on each iteration of the loop:

for /f "delims=" %%# in ('set') do echo %%# 

here are the letters that you can use as tokens.And be careful - you need to use double % in a script and a single in command prompt.

There's one more type of variables that has a % only at the beginning - arguments passed to the script (or a subroutine) - accessible with numbers (or rather digits) - from %0 to %9 where %0 is the name of the script itself.

npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • 1
    That ss64.com link is not accurate. There are many more characters that can be used as FOR variables. See http://stackoverflow.com/a/8520993/1012053 – dbenham Sep 19 '14 at 19:50
  • @dbenham - just took a look also on this `tokens=3* will cause the 3rd and all subsequent items on each line to be processed ` which is also not correct...Shall write to Simon. – npocmaka Sep 19 '14 at 19:56
  • What does start, step, or end do? for example: FOR /L %%parameter IN (start,step,end) DO command –  Sep 19 '14 at 22:43
  • @snipe - this way of `FOR` usage is closest to normal programing languages `FOR` loop.`start` is the first value of `%%parameter` `step` is the sum added to previous value and `end` is ..the end.When the loop reaches the value of the end it stops. – npocmaka Sep 19 '14 at 23:13