You can execute multiple commands in a single batch file by simply listing each command on a new line, allowing the script to process them sequentially. For more complex scenarios, use the
call command to invoke other scripts without exiting the current one, or chain commands with operators like
& for parallel execution and
&& for conditional success-based running.
Basic Sequential Execution
The most straightforward way to run multiple commands is to place them in order within your
.bat or
.cmd file. When you double-click the file, Windows Command Prompt (cmd.exe) reads the file from top to bottom, executing each line as it encounters it. This default behavior handles standard operations such as changing directories, copying files, or launching applications.
For example, if you need to navigate to a specific folder and then list its contents, you would write:
cd C:\Users\Documents
dir
This approach works perfectly for linear workflows where one step must complete before the next begins. However, it does not handle errors automatically; if the
cd command fails because the directory does not exist, the
dir command will still attempt to run in the previous context, which might lead to unexpected results. To mitigate this, you can check error levels or use conditional operators, but for simple tasks, sequential listing is sufficient and highly readable.
Using the Call Command for Sub-scripts
A common pitfall for beginners is assuming that typing the name of another batch file inside a script will return control to the original file after the second one finishes. By default, cmd.exe treats the called file as a replacement for the current process. Once the inner script ends, the outer script terminates immediately.
To prevent this, you must prefix the invocation with the
call keyword. This tells the command processor to execute the target script and then return to the line following the
call statement in the parent script. This is essential when building modular automation tools where one master script orchestrates several smaller helper scripts.
Consider this structure where
part1.bat runs first, followed by
part2.bat, and finally a concluding message:
@echo off
echo Starting Part 1...
call part1.bat
echo Starting Part 2...
call part2.bat
echo All tasks completed.
Without
call, the text "All tasks completed" would never appear because the script window would close upon finishing
part1.bat. This technique is crucial for maintaining flow in complex deployments. You can also pass arguments to these called scripts using the syntax
call script.bat arg1 arg2, allowing for dynamic configuration between modules.
Chaining Commands with Operators
Sometimes you do not want separate lines or even separate files; you may want to combine actions into a single logical line or control execution based on success or failure. The Command Prompt provides special operators for this purpose:
&,
&&, and
||.
The ampersand (
&) separates commands so they run one after another regardless of whether the previous command succeeded. This is useful for quick cleanup or logging tasks that should always happen.
echo Start > log.txt & echo Done >> log.txt
The double ampersand (
&&) creates a dependency. The second command only executes if the first command returns an exit code of zero (success). This is ideal for preventing cascading failures. For instance, you might only want to delete a backup file if the creation of the new backup was successful:
robocopy Source Dest /MIR && del BackupOld.zip
Conversely, the vertical bars (
||) execute the right-hand command only if the left-hand command fails. This allows for basic error handling directly in the command line without needing full
if statements.
ping -n 1 google.com || echo Network unreachable
Understanding these operators allows you to write concise, robust scripts that react to system states dynamically.
Handling Spaces and Paths
When chaining commands or calling external programs, spaces in file paths can break execution. Always enclose paths containing spaces in double quotes. For example,
call "C:\Program Files\App\script.bat" ensures the interpreter treats the entire string as a single argument. Failure to do so often results in "file not found" errors or partial executions. Additionally, ensure your current working directory is set correctly before invoking relative paths to avoid ambiguity.
Frequently Asked Questions
Why does my batch file close immediately after running?
Batch files close automatically once the last command is executed. To keep the window open for debugging, add
pause at the end of the script. This waits for a key press before terminating the session.
Can I run commands in parallel instead of sequentially?
Standard CMD does not support true parallel execution natively. However, you can launch background processes using
start /b to run a command without opening a new window, allowing the main script to continue. Note that synchronization between these processes is limited.
What is the difference between .bat and .cmd extensions?
Functionally, there is no significant difference for modern Windows systems. Both are interpreted by cmd.exe. The
.cmd extension is preferred for newer scripts as it explicitly denotes a command script, while
.bat is legacy but universally supported.
How do I pass variables to a called batch file?
You can pass variables as arguments when calling the script, such as
call child.bat %MY_VAR%. Inside the child script, access these values using positional parameters like
%1. Alternatively, export environment variables using
setx or ensure they are defined in the parent scope before calling.
Is it safe to use call for every nested script?
Yes, using
call is the standard and safe method for nesting batch files. Without it, the parent script exits prematurely. Ensure that called scripts also use
call if they invoke further sub-scripts to maintain the stack integrity throughout the execution chain.