Programming Field

‘&’ (Combine commands) - DOS/Command Prompt Reference

[Windows NT series] Executes the command at the left side and executes the command at the right side in a row.


<command1> & <command2>


Usage of ‘&’

‘&’ executes <command1> and, regardless of its result, executes <command2> in a row. However, if <command1> exits the prompt (session) by using Exit or etc., <command2> will not be executed.

When using ‘&’, the value of Errorlevel (or the environment variable ERRORLEVEL) will be the result (exit code) of <command2> (the last command when concatenating multiple commands with &).

If you connect commands with ‘&’, you should pay attention to the timing of environment variable expansion. The environment variables are expanded before executing any commands, so if executing following command:

set FOOVAR=hello & echo %FOOVAR%

... this command will prints ‘ECHO is on.’ (or ‘ECHO is off.’) in case ‘FOOVAR’ is not set before executing. To avoid this, you should write by using Setlocal and ‘!’ as following:

setlocal enabledelayedexpansion
set FOOVAR=hello & echo !FOOVAR!

On the other hand, the following uses the behavior of those expansion rule:

set HOGEVAR=world
endlocal & set PIYOVAR=Hello %HOGEVAR%

This enables to define ‘PIYOVAR’ outside Endlocal with using ‘HOGEVAR’ and to remove ‘HOGEVAR’. This will result to display ‘Hello world’ on the screen.

If you want to include ‘&’ character itself to the part of command lines, or to print it by using Echo command or etc., enclose with ‘" "’ if you can use ‘" "’, otherwise put ‘^’ character just before ‘&’ character (like ‘^&’).

Note that you cannot use ‘;’ instead of ‘&’.

See also