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


June 04, 2001

Shell Scripting 101, Lesson 6

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

In "Shell Scripting 101, Lesson 5" (http://www.winscriptingsolutions.com, InstantDoc ID 20781), I introduced you to the If command. You‘ll probably use this command frequently in your scripts because its many clauses and switches make it a powerful tool. Here are some examples of how you can use this key command.

Testing for a False Statement
As I discussed in Lesson 5, the If command executes the specified code if the specified condition exists. If you’d rather execute code if a condition doesn’t exist, you can use the If command with the Not clause. The syntax is

If Not Condition CodeToExecute

where Condition is the conditional code and CodeToExecute is the code you want to run if the conditional code evaluates to a false statement.

For example, the following code sample tests whether you’ve installed Windows 2000 or Windows NT into a different directory location:

If Not Exist C:\winnt Echo You’ve installed Windows to
different directory location than the default.

This code sample not only demonstrates the use of If Not but also introduces how to test for the existence of folders and files.

Testing for the Existence of Folders and Files
You can use the If command with the Exist clause to test whether certain folders or files exist. The syntax is

If Exist Condition CodeToExecute

For example, suppose you want to test whether the Winnt folder is on the C drive. You can use the code

If Exist C:\winnt Echo The Winnt folder
is on the C drive.

If that folder exists, the Echo command displays the message The Winnt folder is on the C drive.

To broaden the scope of an existence test, you can use wildcards, such as the asterisk (*), in the folder name or filename. For example, if you can remember the name but not the extension of a file, you can still test for that file’s existence. The code

If Exist C:\boot.* Echo The boot.* file is on
the C drive.

tests whether any file on the C drive has the filename boot.

Testing Whether the Last Command Completed Successfully
You can use the If command with the Errorlevel clause to determine whether the preceding command executed successfully. Most shell-scripting commands return a number, or error-level value, when they execute. The error-level value of 0 indicates success; the error-level value of 1 or higher indicates failure. With the Errorlevel clause, the If command tests whether the preceding command’s error-level value is equal to or greater than the number you specify. You use the syntax

If Errorlevel number CodeToExecute

where number is the number you want the last command’s error-level value to be equal to or greater than. Take, for example, the code

Copy C:\fred.txt C:\temp\fred.txt

If Errorlevel 1 Echo Last command didn’t complete successfully.

If the Copy command returns an error-level value of 1 or higher (i.e., the command failed to copy the C:\fred.txt file to the C:\temp folder), the Echo command displays the message Last command didn’t complete successfully. Because a few shell-scripting commands don’t return error-level values, you need to test your code carefully to ensure the Errorlevel clause is working correctly.

Testing Whether Two Strings Are the Same
You can use the If command to test whether two strings are the same, and if they are, execute the specified code. The syntax for this usage is

If "string1" == "string2" CodeToExecute

where "string1" and "string2" are the strings or environment variables to compare. Note the use of the quotes. When you use the If command to test strings, a good practice to follow is to enclose the strings and environment variables in quotes. The If command will fail if a string contains spaces and you don’t enclose that string in quotes. Similarly, the If command will fail if a variable contains spaces or is empty and you don’t enclose that variable in quotes.

Here’s an example of how to use the If command for string comparisons:

Set EV1=Fred Smith
If "%EV1%" == "Fred Smith"
 Echo These two strings are the same.

The string comparison is case sensitive. If you run the code

Set EV1=Fred Smith
If "%EV1%" == "Fred smith"
 Echo These two strings are the same.

the Echo command won’t execute because the string comparison is a false statement. You can use the /i switch to disable the case sensitivity with code such as

Set EV1=Fred Smith
If /i "%EV1%" == "fred smith"
 Echo These two strings are the same.

If you want to use the If statement to detect a negative condition, you can add the Not clause. For example, the code

Set EV1=Fred Smith
If Not "%EV1%" == "fred smith"
 Echo These two strings are different.

tests whether the two strings are the same. If they aren’t the same, the If command executes the Echo command.

Homework Assignments

  1. Type or copy the lines
  2. Copy C:\fred.txt C:\temp\fred.txt
    If Errorlevel 1 Echo Last command didn’t complete successfully.
    Copy C:\fred.txt C:\temp\fred.txt
    If Not Errorlevel 1 Echo Last command completed successfully.

    into a Notepad file, and save it as ErrorlevelTest.bat. (For step-by-step instructions on how to create and run a .bat file, see "Shell Scripting 101, Lesson 1," http://www.winscriptingsolutions.com, InstantDoc ID 16355.) Run ErrorlevelTest.bat without creating a fred.txt file for the Copy command to copy. Next, create a fred.txt file, place it on the C drive, and run ErrorlevelTest.bat again. Compare the results of the two runs.

  3. Explore what happens when you don’t include quotes around the strings or variables in a string comparison. For example, try running the code
  4. Set EV1=Fred Smith
    If %EV1% == Fred Smith Echo These two strings are the same.

    and see what happens.

  5. Explore what happens when you have an empty string in a string comparison. Try running the code
  6. Set EV1=IF "%EV1%" == "Fred Smith" Echo 
    These two strings are the same.

    and see what happens.

  7. Try to write code that detects whether your OS is NT. Here’s a hint: Use the Set command to locate an environment variable that gives you the OS, and use that variable in an If statement.

End of Article



Reader Comments
<P>I like it. I'm a tech writer with reasonably good technical skills, but tutorials like this help me with documentation, and with my production environment. Thank you!</P>

Barry Cliver October 20, 2003


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
Battery Life Issues Almost Certainly Not Windows 7's Fault

While Microsoft is still investigating a notebook battery life issue that was supposedly caused by Windows 7, some interesting trends have emerged. ...

Getting your iPhone to Sync with Exchange 2003

Follow these steps to use an iPhone with Exchange. ...

Command Prompt Tricks

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


Related Articles Shell Scripting 101, Lesson 10

Shell Scripting 101, Lesson 10

Shell Scripting 101, Lesson 9

Shell Scripting 101, Lesson 8

Task Automation Whitepapers Three Ways to Prevent Insider Risk within Your SCCM-Managed Environment

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

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

Related Events Deep Dive into Windows Server 2008 R2 presented by John Savill

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


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.
 © 2010 Penton Media, Inc. Terms of Use | Privacy Statement