Windows IT Pro is the leading independent community for IT professionals deploying Microsoft Windows server and client applications and technologies.
  
  
  Advanced Search 


April 24, 2001

Shell Scripting 101, Lesson 5

RSS
Subscribe to Windows IT Pro | See More Task Automation Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!

Download the Code Here

Occasionally, you might need to perform math in a shell script. In Lesson 3, I showed you how to use the Set command to create custom environment variables. You can also use the Set command to perform simple math calculations, such as addition, by including the /a switch. This switch tells the scripting engine to evaluate the integers that follow as numerical expressions.

For example, if you run the code

Set /a Fred=2+3
Echo %Fred%

you receive the sum of these two numbers (i.e., 5). If you run the code without the /a switch

Set Fred=2+3
Echo %Fred%

you won't receive a result of 5 but rather the string 2+3. Without the /a switch, you're merely making the Fred environment variable contain the string 2+3.

The Set /a command performs math calculations with integers only. The calculations you can perform with this command are

  • addition (use the + operator)
  • subtraction (use the - operator)
  • multiplication (use the * operator)
  • division (use the / operator)
  • modulus (i.e., the process of dividing two numbers and returning only the remainder—use the % operator)

The Set /a calculations are precise as long as the integers you’re calculating are 10 or fewer digits.

Combining the Set and If Commands
Systems administrators often use the Set /a command in conjunction with the If command when they perform math calculations. The If command executes specific code if a certain condition exists (i.e., the conditional code evaluates to a true statement). The If command has many syntax versions, but the basic syntax is

If Condition CodeToExecute

where Condition is the conditional code to evaluate and CodeToExecute is the code you want to run if the conditional code evaluates to a true statement. When you combine a Set /a command with an If command, you can use these abbreviations:

  • EQU (equal to)
  • NEQ (not equal to)
  • LSS (less than)
  • LEQ (less than or equal to)
  • GTR (greater than)
  • GEQ (greater than or equal to)

For example, if you run the code

Set /a Fred=2+3
Set /a Wilma=2*3
If %Fred% LSS %Wilma% Echo Yes, Fred is less than Wilma

you receive the result Fred is less than Wilma. However, if you run the code

Set /a Fred=2+3
Set /a Wilma=2*3
If %Fred% GTR %Wilma% Echo Yes, Fred is less than Wilma

you don't receive any result because the conditional code evaluates to a false statement.

In Lesson 6, I’ll cover the If statement in greater detail. For now, let's look at a more practical example of how you can use the Set /a and If commands together.

A Practical Example
Suppose you want a script to loop a certain number of times. CountLoops.bat in Listing 1 illustrates how you can use the Set /a and If commands to prompt that script to run a certain number of times.

CountLoops.bat uses several new concepts: counters, the GoTo command, and labels. You can use counters to track the number of times a script completes an operation. For example, you can use counters to capture how many user accounts a script adds or how many files are in a folder. An important point to remember when you use counters is that you need to initialize the counter before you use it by including the command

Set /a counter=0

at the beginning of the script. This command sets an initial value (in this case, 0). If you use the counter without setting an initial value, you can receive some unusual errors.

By default, the scripting engine reads code from top to bottom. However, you can use the GoTo command and labels to change a script’s flow of execution—you can jump to any location in the script. You place the GoTo command at the point at which you want to jump to a different part of the script. The label marks the spot to which you want to jump. The GoTo command’s syntax is simply

GoTo :Label

You can use any term for the label as long as you preface it with a colon (:). Although you can use spaces in the label, you can’t use commas, semicolons, or other separators. The label can be any length. However, the scripting engine reads only the first eight characters, so it reads the labels :MyLabel01 and :MyLabel02 both as :MyLabel0, which can cause errors in a script.

In Listing 1, the code’s flow needs to return to the top of the script whenever the value of the counter variable is less than 10. So, I used the GoTo command with the label :Top to move the flow to that point, where the execution again proceeds downward.

Homework Assignments

1. Run the commands

Set /?|More

and

If /?|More

to see all the options that the Set and If commands provide.

2. Download CountLoops.bat by clicking the Download the code link in the Article Information box. Comment out the counter initialization line

Set /a counter=0

by prefacing it with a double colon (::) or the word Rem. Run the script several times in the same command-shell window to see the errors that result.

End of Article



Reader Comments
The Shell scripting 101 pages are an excelent resource for all sorts of tasks. As a newly appointed sysadmin I need to expand my skills in this area and constanly end up at this site when browsing the web for tips. From now on I will just come straight here, and give google a rest!

Steven Wood July 06, 2004


You must be a registered user or online subscriber to comment on this article. Please log on before posting a comment. Are you a new visitor? Register now




Top Viewed ArticlesView all articles
Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...

WinInfo Short Takes: 4th of July Special Edition

An often irreverent look at some of the week's other news, including a shortened work week thanks to the 4th of July, expensive Windows 7 pricing, Bing's modest monthly gains, IE 8 heading to work, Steve Jobs back at Apple, and so much more ...

Google Wave Emulates Trends of Changing World

As collaboration continues to increase, the world and how individuals view information is evolving. What does that mean for IT? ...


Related Articles Shell Scripting 101, Lesson 10

Shell Scripting 101, Lesson 9

Shell Scripting 101, Lesson 8

Shell Scripting 101, Lesson 7

Task Automation Whitepapers Business Innovation with Data Center Transformation

Batch Job Scheduling and .NET in 2008

Continuous Data Protection and Recovery for Microsoft Exchange

Related Events WinConnections and Microsoft® Exchange Connections

Check out our list of Free Email Newsletters!

Task Automation eBooks Spam Fighting and Email Security for the 21st Century

A Guide to Windows Certification and Public Keys

Keeping Your Business Safe from Attack: Patch Management

Related Task Automation Resources Introducing Left-Brain.com, the online IT bookstore
Looking for books, CDs, toolkits, eBooks? Prime your mind at Left-Brain.com

Discover Windows IT Pro eLearning Series!
Clear & detailed technical information and helpful how-to's, all in our trademark no-nonsense format

Test Drive IT Solutions and Get Free Music Downloads
Solve your toughest IT problems with these free downloads and receive 5 free music downloads!


Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro DevProConnections IT Job Hound ITTV
IT Library Technology Resource Directory Connected Home asp.netPRO Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 © 2009 Penton Media, Inc. Terms of Use | Privacy Statement | Reprints and Licensing