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 


March 01, 2001

Shell Scripting 101, Lesson 3

RSS
View this exclusive article with VIP access -- click here to join |
See More Task Automation Articles Here | Reprints | Or sign up for our VIP Monthly Pass!

Download the Code Here

In Lesson 2, I showed you how to use system-provided environment variables such as USERNAME and COMPUTERNAME to retrieve information about currently logged-on users and their computers. You can also use environment variables for two additional purposes:

  • You can create an environment variable to represent a specified value.
  • You can use an environment variable to temporarily hold a value so that you can pass information to a script as an argument.

Creating Environment Variables to Represent a Specified Value
To create environment variables to represent a specified value, you need to use the Set command. Using the Set command with environment variables is a great way to make your lines of code shorter, easier to read, and simpler to change.

For example, suppose you’ve updated a file called listofstuff.txt on your server (\\H10server\stuff\listofstuff.txt) and now you must update a copy of that file on the D drive (D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt). The script must delete the old file if it exists, then copy the updated file. Listing 1 shows how this script looks if you hard-code the file’s pathname each time. As Listing 1 illustrates, this code is long and difficult to read. In addition, this code is difficult to edit if you need to change the D drive’s pathname because you must change each occurrence.

A better approach is to create an environment variable for the commonly occurring pathname. As the script in Listing 2 shows, you can use the Set command to create the StuffFile environment variable, which contains the pathname "D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt". Enclosing the pathname in quotation marks handles any spaces in the path. Without quotation marks, a pathname with a space will cause the script to fail.

After you create the environment variable, you simply specify that variable’s name enclosed in percent (%) signs each time you want to include the pathname. The percent signs let you retrieve and use the environment variable’s value.

Creating an environment variable instead of hard-coding the pathname can save a lot of space, especially in scripts that use long pathnames often. Even better, if the pathname changes, you need to change only one occurrence: the pathname in the Set command.

Limiting the Environment Variable’s Scope
By default, an environment variable you create with the Set command affects your entire system—that is, the environment variable has a global scope. You can use the Setlocal and Endlocal commands to make an environment variable affect only that script or a portion of it. In other words, you make the environment variable have a local scope. I highly recommend that you use the Setlocal and Endlocal commands to keep your Set commands from accidentally affecting System variables or causing a script that’s run in the same command shell window from inheriting values from an earlier run of a similar script.

To make an environment variable apply to an entire script, you place the Setlocal command before the Set command and the Endlocal command at the end of your script, as Listing 3 shows. To make the environment variable apply to a certain portion of the script, you place the Setlocal command before the Set command and the Endlocal command at the point at which you want the environment variable’s scope to end. Take, for example, the code in Listing 4. The Echo %TestVariable% command is no longer under the environment variable’s scope. As a result, if you run the code in Listing 4, the %TestVariable% won’t have a value. As this example illustrates, if you’re limiting the environment variable’s scope to only a portion of a script, you need to make sure that the code you exclude doesn’t need that variable’s value. For this reason, I recommend that you use the Setlocal command before any Set commands and the Endlocal command at the end of your script.

Using an Environment Variable to Temporarily Hold a Value
A special group of environment variables are the argument-holding variables %0 through %9. You can use these variables to bring input into your script at runtime. For example, suppose you want to run the script in Listing 2, but you want to change the pathname each time the script runs. Instead of opening the file and editing the Set command each time, you can use an argument-holding variable. As the script Test.bat in Listing 5 shows, you don’t include the Set command and you use %1 instead of %StuffFile%. Then, when you run Test.bat, you type the launch command

Test.bat "D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt"

in the command-shell window. When the script runs, the %1 variable brings your external input (i.e., "D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt") into the script.

If you want to use additional arguments, you add the next consecutive argument-holding variable to the code and that variable’s value to the launch command. You’re limited to 10 arguments (i.e., %0 through %9). You might be wondering, "What is the value of %0?" To learn the answer and to see how to use two arguments, create the script Test2.bat that Listing 6 shows. Then use the launch command

Test2.bat "The First Argument" "Another Argument"

to run Test2.bat. As Figure 1 shows, if you launch the script from the directory in which you placed the script, the value of %0 is the script’s filename. If you launch the script from a different directory, the value of %0 is the script’s pathname.

Practice Exercises

  1. Write code that combines a system-provided environment variable with a user-created environment variable. For example, write code that first uses the TEMP environment variable to run the Dir command against your Temp folder, then uses the Set command to create an environment variable that points to the folder in which you want to copy all the .tmp files.


  2. In the pathname "D:\stuff\morestuff\mystuff\yourstuff\lotsofstuff\listofstuff.txt" in Listing 2, remove the quotation marks and intentionally insert a space. Run the code, and observe the results.

End of Article



Reader Comments
Exellent Lessons
Thanks for providing such articles

Ananth August 07, 2001


I'm naive in scripting. This site really helps me to learn a lot about scripting. It's really quite good and easy to understand. Thank you very much for publishing such excellent articles.

Sankar V April 10, 2002


Yet another reason why I read my Windows & .NET Newsletter first thing in the morning right after the boss's emails. This series is a great help. Keep up the great work!

Jimmy April 21, 2002


You must log on before posting a comment.

If you don't have a username & password, please 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. ...

Have New Features Made Exchange Server Backups Unnecessary?

Cluster continuous replication and Volume Shadow Copy Service might have made backups unnecessary in Exchange 2007, but will admins feel comfortable without a dedicated backup solution in place? ...

Ballmer: Yahoo! No Bargain at Any Price

At Microsoft's annual shareholder meeting this week, CEO Steve Ballmer emphatically closed the door on the possibility that his company was interested in purchasing ailing Internet giant Yahoo!. His frank assessment of the situation sent Yahoo!'s stock ...


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 Essential Guide to E-discovery and Recovery for Microsoft Exchange

Continuous Data Protection and Recovery for Microsoft Exchange

Protecting (You and) Your Data with Exchange Server 2007

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