I try to understand how multiple commands in a single command line in a batch file work.
dir & md folder1 & rename folder1 mainfolder
And other case with similar commands, but &
substituted with &&
.
dir && md folder1 && rename folder1 mainfolder
1. What is the difference between this two cases?
Other thing I want to ask:
One-liner batch.bat
:
dir & md folder1 & rename folder1 mainfolder
Multi-liner batch.bat
:
dir
md folder1
rename folder1 mainfolder
2. Are this one-liner and multi-liner equal in terms of batch file procedure?
And one more thing I would like to know:
3. If I call other batch files from a main.bat, are they run independent and simultaneously? Main batch file does not wait for ending procedures in other batch files? How to do that?
&
between two commands simply results in executing both commands independent on result of first command. The command right of&
is executed after command left of&
finished independent on success or error of the previous command, i.e. independent on exit / return value of previous command.&&
results in a conditional execution of second command. The second command is executed only if first command was successful which means exited with return code 0.For an alternate explanation see Conditional Execution.
is therefore equal
A multiline replacement for
would be
if not errorlevel 1
means the command before did not terminate with an exit code greater 0. As the commandsdir
andmd
never exit with a negative value, just with 0 or greater (as nearly all commands and console applications) and value 0 is the exit code for success, this is a correct method to test on successful execution ofdir
andmd
. See the Microsoft support article Testing for a Specific Error Level in Batch Files.Other helpful Stack Overflow topics about errorlevel:
Care must be taken on mixing unconditional operator
&
with conditional operators like&&
and||
because of the execution order is not necessarily the order of the commands on command line.Example:
This command line is executed as:
The ECHO command is always executed independent on result of execution of first DIR whereas second DIR is executed only if first DIR fails like on Windows XP or the user's profile folder is not on drive C: or not in a folder
Users
at all.It is necessary to use
(
and)
on executing ECHO only if first DIR fails after second DIR independent on result of second DIR.This command line is executed as:
For the answer on third question see my answer on How to call a batch file in the parent folder of current batch file? where I have explained the differences on running a batch file with command
call
or withstart
or with none of those two commands from within a batch file.