Difference between revisions of "Windows batch"

From Ever changing code
Jump to navigation Jump to search
Line 6: Line 6:
  ) else (
  ) else (
     copy /a e + /a %TMP%=/a e
     copy /a e + /a %TMP%=/a e
)
;Environment variables in batch files are expanded when a line is parsed.
In the case of blocks delimited by parentheses (as your if defined) the whole block counts as a "line" or command and it is read once. This means that all occurrences of %FOO% are replaced by their values before the block is run. Therefore %FOO% will be replaced by nothing as it was not set.
To solve this you can enable delayed expansion:
setlocal enabledelayedexpansion
Delayed expansion causes variables delimited by exclamation marks (!) to be evaluated on execution instead of parsing which will ensure the correct behavior in our case:
if not defined BAR (
    set FOO=1
    echo Foo: !FOO!
  )
  )



Revision as of 19:06, 27 June 2014

IF and ELSE

The else needs to be on the same "line" as the if. From IF /? 'The ELSE clause must occur on the same line as the command after the IF.'
if "zz"=="TRUE" (
    copy /a zz + /a ee=/a zz
) else (
    copy /a e + /a %TMP%=/a e
)
Environment variables in batch files are expanded when a line is parsed.

In the case of blocks delimited by parentheses (as your if defined) the whole block counts as a "line" or command and it is read once. This means that all occurrences of %FOO% are replaced by their values before the block is run. Therefore %FOO% will be replaced by nothing as it was not set.

To solve this you can enable delayed expansion:

setlocal enabledelayedexpansion

Delayed expansion causes variables delimited by exclamation marks (!) to be evaluated on execution instead of parsing which will ensure the correct behavior in our case:

if not defined BAR (
    set FOO=1
    echo Foo: !FOO!
)


Text manipulation

  • color 0a - changes text to green
  • mode con: cols=80 lines=50 - changes cmd.exe window, no scroll available, type mode to display the current settings

References