Windows IT Pro is the authoritative and independent resource for windows nt, windows 2000, windows 2003, windows xp. Features a collection of resources and magazines for windows IT professionals.
  
  
  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 log on before posting a comment.

If you don't have a username & password, please register now.




Top Viewed ArticlesView all articles
WinInfo Short Takes: Week of November 24, 2008

An often irreverent look at some of the week's other news, including a Vista Capable dismissal request, Zune price reductions, Morrow musings, Novell and Microsoft sitting in a tree ... two years later, Yahoo!, IE 6 on Windows Mobile, and so much more ...

Command Prompt Tricks

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

PsExec

This freeware utility lets you execute processes on a remote system and redirect output to the local system. ...


Related Events Virtualization Management

Virtualization for Mission-Critical BI with SQL Server

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 Become a VIP member of the Windows IT Pro community!
Get it all with the VIP CD and VIP access. A $500+ value for only $279!

Subscribe to Windows IT Pro!
Solve your toughest technical problems with our experts and access 10,000 + articles online. 30% off

Monthly Online Pass - Only $5.95!
Get instant access to 10,000+ articles from Windows IT Pro Magazine!

TechNet Virtual Labs
Evaluate and test Microsoft's newest products.


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 Windows Dev Pro IT Job Hound ITTV
IT Library Technology Resource Directory Connected Home Windows Excavator Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2008 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing