The For command is a powerful shell scripting command because it’s versatile. Let’s look at some common uses of the For command. Specifically, let’s look at how to use the For command with the /d switch and with the /f switch. Along the way, you’ll learn about the Ping command.
Using the For /d Command
Suppose you want to test the connections to five file servers (i.e., fileserv1, fileserv2, fileserv3, fileserv4, and fileserv5). If you’ve installed the TCP/IP protocol in your network, you can use the Ping command to verify the connections. The Ping command’s syntax is
Ping computername
where computername is the name of the server you want to ping. By default, the Ping command sends up to four ping packets to the computer. Pinging five file servers up to four times can waste time and bandwidth, so let’s ping each server only once. To change the default number of ping packets, you use the –n parameter, which lets you specify the number of ping packets to send. To ping each server once, you can use the code
Ping -n 1 fileserv1
Ping -n 1 fileserv2
Ping -n 1 fileserv3
Ping -n 1 fileserv4
Ping -n 1 fileserv5
To shorten this code from five lines to one line, you can use the For command. The For command has different syntaxes for different purposes. In this case, the syntax to use is
For [/d] %variable in (set) Do command
You use this particular syntax to iterate through a set of files or directories and perform a command for each file or directory in that set. Let’s look at the individual segments in this syntax.
For [/d]. When you use the For command, the command processor assumes you want to iterate through files by default. To tell the command processor you want to iterate through directories, you include the optional /d switch. (In syntax, placing a switch or parameter in square brackets means it’s optional.) In the For command for the ping test, you need to include the /d switch.