How to Group Multiple Commands in cmd.exe
Article Posted by Pramod S Nair for www.wisdombay.com
This article is an attempt at explaining the task of getting multiple commands executed in a sequential way in cmd.exe. This article also looks at executing groups of commands based on the status of (success or failure) of any previous commands.
First of all let's have a look at Chaining Multiple commands.
Syntax : command1 & command2
For example if you need to change the current directory to a specific directory and then list all the .mp3 files there, you can go for the below given command
C:\ cd mymusic & dir *.mp3
So for chaining multiple commands it's pretty simple, just add an '&' in between the commands that you want to chain.
Conditional execution of chained commands
The below given syntaxes can help you in situations were you need to execute some chained command based on the outcome of some previous command. These come handy when you are writing Scripts or Batch files.
1. Syntax : Command1 && Command2
This makes sure that command2 is executed only if command1 is executed successfully.
dir *.bat && echo "Batch Files Found"
The above code will output 'Batch Files Found' only if the first command 'dir *.bat', executes successfully .i.e, if there are some batch files in the current directory. If first command returns no batch file then second command is not executed.
2. Syntax : Command1 || Command2
This makes sure that command2 is executed only if command1 is not executed successfully. So in this case command2 is executed only when command1 fails.
dir *.bat || copy d:\usefulbats\*.bat .
The above code will copy the batch files from d:\usefulbats to current directory only if the first command i.e 'dir *.bat' fails. So if there is no batch file in current directory it copies the batch files from d:\usefulbats to current directory
Grouping Command Chains
This section explains, how you can combine and exactly control the order in which the command chain is executed.
hostname & ver & vol > info.txt
The above example attempts to output the hostname, operating system version information and volume information to a text file called info.txt. But only the last command's output is channeled to the text file. So to archive the desired result use the following command group
(hostname & ver & vol) > info.txt
Grouping can also be used with conditional chained commands also, with a syntax like. (command1 & command2) && (command3)
So i am winding up this paper on using Grouped commands in cmd.exe for now. Will catch up with you later with more technical papers like these in the future