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


October 2006

10 Keys to Command Shell Scripting

Polish and error-proof your scripts
RSS
Subscribe to Windows IT Pro | See More Performance Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!

6. Use the Setlocal and Endlocal Commands
The Setlocal command copies all environment variables, and Endlocal restores all variables to the values they had before the script started. Endlocal also deletes any variables the script created. Using both these commands makes a script more self-contained and ensures that a script "cleans up after itself" by restoring environment variables to their original values and deleting variables the script created.

Also, you can use the Setlocal Enableextensions command to make sure that command extensions are enabled. Command extensions are enhancements to a group of Cmd.exe internal commands (e.g., If, For, Call) that provide expanded capabilities beyond the Command.com commands that have the same names. Command extensions are enabled by default, but in the rare cases in which command extensions are disabled, the Setlocal Enableextensions command ensures that command extensions are enabled. To see more information about command extensions, type Cmd /? at a command prompt.

7. Use the Escape Character When Needed
Cmd.exe uses the caret (^) as an escape character that bypasses the normal meanings of reserved shell characters. For example, the ampersand (&) is the command separator—it lets you put multiple commands on one line. If you intend to use the & literally, you must "escape" its normal meaning by prefacing it with the ^. So in the line

Echo The ^& character is the command separator

the ^ causes the shell to bypass the normal interpretation of the character that follows. You need to escape the characters ( ) < > ^ & and |. You don't need to escape these characters if they occur inside a quoted string.

8. Don't Use the Exit Command Without the /b Option
Without the /b option, the Exit command closes the current shell. If someone starts a Cmd.exe session and executes a script that contains the Exit command, the current shell will abruptly close. The Exit /b command closes the current script without terminating the current shell. For more information about the Exit command, type the command Exit /? at a command prompt.

9. Watch Out for If Errorlevel
The If Errorlevel command tests the exit code of the last command that was executed. Scripts can test a program's exit code and behave accordingly. For example, consider the following script code:

Myprogram
If Errorlevel 1 Goto :ERROR 

In these lines, the Goto command will execute if Myprogram.exe returns an exit code greater than or equal to 1. In other words, "If Errorlevel n" doesn't mean "if the last exit code is exactly n;" it really means, "if the last exit code is at least n." Because of this behavior, make sure to test exit codes in descending order (highest to lowest). To test for a specific exit code, use the ERRORLEVEL dynamic variable instead of If Errorlevel. Note that the If Errorlevel command is different from the ERRORLEVEL variable listed in Table 1. The If Errorlevel command is backward compatible with Command.com's If Errorlevel command; the ERRORLEVEL variable is only available in Cmd.exe.

10. Be Aware of Start's Quirks
The Start command starts a program or a command in a new console window. However, if you try to start a program from a directory that contains spaces (or if the program's name contains spaces), the Start command won't behave as you might expect. For example, the following command

Start "C:\Program Files\Microsoft 
  Office\Office11\Winword.exe" 

doesn't start Microsoft Word, as you might expect. Instead, the Start command will open a new Cmd.exe session with the quoted string as the title of the console window. This behavior occurs because the Start command uses the first quoted string on its command line as a console window title.

To work around this quirk, use a pair of quotes to specify a blank title, then follow the title with the program you want to run. The corrected Start command will look like this:

Start "" "C:\Program Files\Microsoft 
  Office\Office11\Winword.exe" 

Avoid Potential Problems
Cmd.exe shell scripts are widely used. With these guidelines under your belt, you can write more robust shell scripts and avoid common problems.

End of Article

   Previous  1  2  [3]  Next  


Reader Comments
Hi all, note that the URL has changed for the utilities written by the author. The URL is now http://www.westmesatech.com. Regards, Bill

AbqBill March 13, 2008 (Article Rating: )


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
WinInfo Short Takes: Week of November 23, 2009

An often irreverent look at some of the week's other news, including some post-PDC some soul searching, a Google Chrome OS announcement and a Microsoft response, Windows 7 off to a supposedly strong start, the Jonas Brothers and Xbox 360, and so much more ...

Command Prompt Tricks

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

2009 Windows IT Pro Editors' Best and Community Choice Awards

Picking a favorite product from an impressive crowd of competitive offerings is never an easy task, and such was the case with our Editors' Best and Community Choice awards this year. ...


Scripting Whitepapers From Development to Production: Streamlining SharePoint Deployment with DocAve Deployment Manager

Related Events Cutting Costs with Client Management

7 Ways To Get More From Your SharePoint Deployment Now

Introduction to Identity Lifecycle Manager "2"

Check out our list of Free Email Newsletters!

Scripting eBooks Keeping Your Business Safe from Attack: Encryption and Certificate Services

Best Practices for Managing Linux and UNIX Servers

Building an Effective Reporting System

Related Scripting 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


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
Left-Brain.com Technology Resource Directory asp.netPRO ITTV Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 © 2009 Penton Media, Inc. Terms of Use | Privacy Statement