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!

Shell scripts are plain-text files that a command shell interprets as a series of commands to be executed in sequence. Shell scripts have a long history: The Command.com shell in MSDOS has supported simple batch-file scripting since the early 1980s. Released with Windows NT in 1993, the text-based Cmd.exe command shell supports a script language similar to the batch language in Command.com. Despite its age, Cmd.exe shell scripting is still a useful tool in the IT professional's arsenal. For example, a simple shell script with a For command can transform a command that works with only one computer or username at a time on the command line into a command that can step through a text file and execute the command for each line in the file. Because shell scripts are plain-text files that contain a series of commands, they are easy to create, modify, and understand. However, these scripts' simplicity can also be a liability. A carelessly written shell script can cause potentially serious problems. I've seen shell scripts that make incorrect assumptions about the underlying OS or environment that, at best, prevent them from working correctly, or at worst, wreak havoc on an unsuspecting system. To help you avoid such problems, I've written the following set of 10 guidelines for creating more robust scripts that can work correctly in various environments.

1. Use Environment Variables When Possible
When you use a variable in a script, you enclose the variable's name between percent signs (%), and when the shell script runs, the percent signs and the text between them will be replaced with the variable's data. Using variables makes the script's code more generic—it has a better chance of running successfully on different computers. For example, you should never "hard-code" the Windows installation directory name in a shell script. Instead, you should use the SystemRoot variable, which will always point to theWindows installation directory. So, the command

Echo %SystemRoot% 

will display the contents of SystemRoot (i.e., the Windows installation directory).

In several cases, I've seen shell scripts that used C:\WINDOWS to refer to the Windows installation directory. If Windows isn't installed in C:\WINDOWS (e.g.,Windows 2000 and earlier are installed in \WINNT), the script won't work properly. Environment variables make life easier for programmers and script writers.

To see a list of environment variables, type the Set command at a command prompt. Some variables don't appear in the list generated by the Set command because they're dynamically generated by Cmd.exe. Table 1 shows a list of these variables. As with other environment variables, enclose these variables between percent signs. For example, the following line in a script will display the current date and time:

Echo %DATE% %TIME% 

2. Don't Expect Legacy Command.com Batch Files to Work in Cmd.exe
If you're accustomed to writing batch files for the MS-DOS or Windows 9x/Me platforms, be aware that some batch-file commands you're used to don't exist in the newest versions of Windows. The Choice and Deltree commands are the two most common examples. Review your old batch files to make sure they work correctly in a Cmd.exe window. Table 2 shows some suggested replacements for Choice and Deltree. Most of these replacements have a different-syntax than the commands they're replacing, so you'll need to modify your scripts accordingly.

3. Use the .cmd Extension for Cmd.exe Shell Scripts
Command.com batch files require the .bat file extension. Cmd.exe can also use the .bat extension, but in Cmd.exe's more powerful scripting language, many commands aren't compatible with Command.com. Thus, a .bat file that you design to work with Cmd.exe might fail if a user tries to execute it in Command.com (e.g., in Windows 98). One way to avoid this potential problem is to use .cmd as a shell script extension. Because Command.com doesn't recognize the .cmd extension, it simply won't execute a batch file if the filename ends with .cmd.

   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
The Memory-Optimization Hoax

Don't believe the hype. At best, RAM optimizers have no effect. At worst, they seriously degrade performance. ...

8 Million People Lose Private Information Overnight

If you stayed at a Best Western hotel anytime since 2007 then your private information is now for sale to fraudsters all over the globe. Ouch. ...

Microsoft Makes Anti-Piracy Changes to Windows XP

Microsoft late Tuesday made changes to its Windows Genuine Advantage (WGA) Notifications anti-piracy service in Windows XP, a change that should begin appearing on users' desktops over the next few months. The company says it made the changes in order ...


Related Events 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.

Job Openings in IT


ADS BY GOOGLE SPONSORED LINKS FEATURED LINKS

Maximize your SharePoint Investment – 8 Cities
Discover best practices and tips for both architecting and administering SharePoint. Early Bird Price of $99 through Sept 15th.

Find a new job now on the all new IT Job Hound!
Search jobs, post your resume, and set up job e-mail alerts!

Master SharePoint with 3 eLearning Seminars
Learn how to build a better SharePoint infrastructure and enable powerful collaboration with MVPs Dan Holme and Michael Noel. Register today!

Top Tools for Virtualization Disaster Recovery & Replication
View this web seminar on August 14th to learn about two tools that will result in faster backup and restore with P2V disaster recovery.

SharePointConnections Conference Fall 2008
Don’t miss the premier event for Microsoft IT Professionals in Las Vegas, November 10-13. Register and book your room by August 25 and receive a FREE room night (based on a three night minimum stay).

VMworld 2008 - Sign Up Today!
Join your peers on September 15-18 at The Venetian Hotel in Las Vegas as VMware hosts VMworld 2008, the leading Virtualization event.



Entrust Unified Communications Certs
Secure Exchange 2007 and save 20%. Now through Sept. 2008.

Increase Application Performance
Free White Paper by Editor's Best winner, Texas Memory Systems.

Need to convert between XML, DBs, EDI, and Excel? Try MapForce free!
Drag & drop to transform between popular data formats – get results instantly or generate code.

Microsoft® Tech•Ed EMEA 2008 IT Professionals
Advance your thinking with new ideas and practical real-world solutions at Microsoft’s FIVE day technical infrastructure conference 3-7 Nov., 2008. Register before 26 September 2008 to save €300.

Order Your SQL Fundamentals CD Today!
Learn how to use SQL Server, understand Office integration techniques and dive into the essentials of SQL Express and Visual Basic with this free SQL Fundamentals CD.

Are You Really Compliant with Software Regulations?
View this web seminar that will help you with compliance best practices and check out a management solution to assure that you won’t be in jeopardy of an audit.

Virtualization Congress Oct. 14-16 in London
Don't miss Virtualization Congress, the premiere EMEA conference dedicated to hardware, OS and application virtualization. Oct. 14-16.
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 Technical Resources 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