Programming Field

‘( )’ (Parentheses (Grouping)) - DOS/Command Prompt Reference

[Windows NT series] Used to combine multiple commands in multiple lines.


<command-1>, <command-2>, ...

Specifies any command. Normally specifies one command (command block) per one line. ‘( )’ can be nested.

Note that indentation is optional.


Usage of ‘( )’ 1 Usage of ‘( )’ 2

For commands, such as If and For, that accepts any commands, you can use ‘( )’ to specify multiple commands as one ‘command block’ as if the block is one command. Other than If, you can also use ‘( )’ where a command line is required as part of the syntax such as ‘||’ and ‘&’.

* Even if the command accepts the command line, you cannot use ‘( )’ for external commands such as Forfiles. The use of ‘( )’ is limited for internal (built-in) commands which cmd.exe interprets directly.

In addition, the closing parentheses is treated as end of command block. This is important for internal (built-in) commands; using ‘( )’ is necessary to mark the end of the command block, based on internal commands' ‘interpreting up to newline character or end of block as entire command’. For example, when writing ‘If <compare> ... Else ...’ in oneline, the command line before Else must be enclosed in ( ).

The exit code of ( ) block will be the one of the last executed command.

Note that when ‘%’ is in ( ) block, the environment variable expansion of ‘%’ will be performed before executing all commands in ( ). To expand the environment variable on each command execution, consider using Setlocal and ‘!’.


Sample 1

if "%MYVAR%"=="Hello" (
    echo Hoge
    echo Piyo

When environment variable ‘MYVAR’ contains ‘Hello’, ‘Hoge’ and ‘Piyo’ are printed line by line.

Sample 2

foo.exe || (
    echo Failed.

When ‘foo.exe’ exits with the exit code other than 0 (i.e. on failure), this executes ‘cleanfoo.exe’ and prints ‘Failed.’. Due to the operator ‘||’, when ‘foo.exe’ returns the exit code 0, ‘cleanfoo.exe’ will not be executed and ‘Failed.’ will not be printed.

Sample 3

    echo Do something...
) && doSomething.exe

Displays ‘Do something...’, executes ‘prepareSomething.exe’, and executes ‘doSomething.exe’ only if ‘prepareSomething.exe’ exits with the exit code 0 (i.e. on success). Due to the operator ‘&&’, when ‘prepareSomething.exe’ returns the exit code other than 0, ‘doSomething.exe’ will not be executed.

Note that if you swap the Echo line and the ‘prepareSomething.exe’ line in this example, ‘doSomething.exe’ will be always executed (the exit code of Echo will be treated as 0 even though ERRORLEVEL value is other than 0).

Sample 4 (Batch file)

setlocal enabledelayedexpansion
if exist "%~f1%~2" (
    set "OUTFILE=%~f1%~n2.out"
    myparse.exe "%~f1%~2" "!OUTFILE!"

[Extensions] To use (write and read) the environment variable in ‘( )’, uses ‘!’ (delayed environment variable expansion) instead of ‘%’ to read the environment variable.