Programming Field

‘!’ (Delay-use environment variable) - DOS/Command Prompt Reference

[Windows NT series] [Extensions] Used to delay expansion of environment variables in the command line such as If, For, or multiple commands concatenated with ‘&’ character or etc. It requires to enable delayed environment variable expansion. (Please see the description of Setlocal.)

Syntax

!<value-name>!

The syntax is the same for ‘%’ (‘%FOO%’ is replaced with ‘!FOO!’).

* Only ‘!<value-name>!’ style can be used. (You cannot use such as ‘!1’.)

Details

For If and For commands, you can specify an additional command line. The Command Prompt (cmd.exe) will expand environment variables when the entire command line (command block) is passed, so when the environment variables exist in an additional command line of If and For, the variables are expanded before executing the commands (If, For, etc.). For example:

if "%VAR%"=="" (
    call hoge.bat
    if "%VAR%"=="" (
        echo Failed.
        exit /B 1
    )
)
...

This sample intends that the program executes ‘hoge.bat’ when an environment variable ‘VAR’ is empty (or not set), and prints ‘Failed.’ and exits if ‘VAR’ is still empty after execution. However, Command Prompt expands all environment variables in the command line (command block), so if ‘VAR’ is empty, the above sample is executed as:

if ""=="" (
    call hoge.bat
    if ""=="" (
        echo Failed.
        exit /B 1
    )
)
...

and ‘Failed.’ is printed and the prompt exits even if ‘hoge.bat’ sets ‘VAR’. Therefore, writing the program as:

if "%VAR%"=="" (
    call hoge.bat
    if "!VAR!"=="" (
        echo Failed.
        exit /B 1
    )
)
...

enables to get the intended behavior; the environment variable expansion in the third line ‘If’ is done after executing ‘hoge.bat’.

The syntax of ‘!’ is the same for ‘%’, including the extended syntax (e.g. !FOO:~1,3!). Please see ‘%’ page for the syntax, or For page for the samples.

See also