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


April 02, 2001

Shell Scripting 101, Lesson 4

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

Download the Code Here

Shell scripting commands often produce output. By default, the system directs a command's output to the console screen. For example, if you run the command

Echo Fred was here

the screen displays the text Fred was here. However, you can easily redirect a command's output to a file with redirection symbols. Two commonly used redirection symbols are the greater than (>) sign and the double greater than (>>) sign.

The > and >> Redirection Symbols
To redirect a command's output to a file, you place the > redirection symbol after the command, then specify the file after the symbol. For example, the command

Echo Fred was here > C:\fredreport.txt

sends the Echo command's output (i.e., the text Fred was here) to the fredreport.txt file on the C drive rather than displaying the output on screen. If this text file doesn't exist, the system automatically creates it. If this text file already exists, the system overwrites the file's existing content with the command's output. Thus, if you run the Echo Fred command three times, then examine the content of C:\fredreport.txt, you'll find only one line of text. Because the system overwrites existing content, the > redirection symbol is useful when you want to create a report and delete any old version that might exist.

If you want to append a command's output to a file's existing content, you can use the >> redirection symbol. For example, the command

Echo Barney was here >> C:\barneyreport.txt

appends the text Barney was here to the existing content of C:\barneyreport.txt if that text file already exists. If that text file doesn't exist, the system automatically creates it and adds the command's output. If you run the Echo Barney command three times, then examine the content of C:\barneyreport.txt, you'll find three lines of text. Because the system appends rather than overwrites content, the >> redirection symbol is useful when you want to create a report in which you plan to add text, either during the current script run or in a future script run.

Let's experiment with adding text to an existing report during a script run. Open Notepad. Type these three lines

Echo Pebbles was here > C:\pebblesreport.txt
Echo. >> C:\pebblesreport.txt
Echo Pebbles was here again>> C:\pebblesreport.txt

into the Notepad file. Select Save in the File menu. In the Save As dialog box that appears, type Pebbles.bat in the File name text box. Leave the default entry, Text Documents (*txt), in the Save as type text box. From the Save in drop-down menu, select Desktop. Click Save, then close Notepad.

You've now created the script Pebbles.bat. Here's how the script works. The first line of code uses the > redirection symbol to create the file C:\pebblesreport.txt, then adds the text Pebbles was here to that file. The next line inserts a blank line into the file. By placing a period directly after the Echo command, you're telling the system to output a blank line, which the >>redirection symbol appends to the file. The last line appends the text Pebbles was here again to the file.

Let's run Pebbles.bat. On your desktop, position the file and your command shell window so that both are visible in the screen. Drag the file onto the command shell window. Click the command shell window so that you see the cursor, then press Enter to run Pebbles.bat. Figure 1 shows the content you'll see if you open pebblesreport.txt.

Redirection Options
Up to this point, you've redirected the various commands' output to a text file. You're not limited to text files, though; you can redirect a command's output to many types of files. You can even redirect command output to NUL.

Redirecting output to different file types. You can redirect a command's output to many different file types. However, you might need to provide special formatting instructions. For example, Listing 1 contains a script, HelloWorld.bat, that redirects the Echo commands' output to an .html file. Note that, in addition to using the Echo command with text, the script uses the Echo command with the USERNAME and COMPUTERNAME environment variables that I discussed in "Shell Scripting 101, Lesson 2," Instant Doc ID 19840.

To format the .html file, the script uses HTML code to specify the headers and body text. Because HTML code uses several symbols (e.g., <, >, /) that the shell scripting language reserves as special shell characters (i.e., characters that have special meaning in the Windows system), the script uses a caret (^) to flag, or escape out, those HTML symbols. The caret tells the system to treat the item that follows as an HTML symbol and not a reserved shell character.

To see a sample .html file that HelloWorld.bat produces, you can download and run this script on your machine. To download the script, click the Download the code link in the Article Information box. After you copy HelloWorld.bat from the 20530.zip file to your desktop, execute the script following the instructions I gave you for running Pebbles.bat.

Redirecting output to NUL. In the sample code thus far, you've redirected output that you need to complete a task, such as creating a report. However, commands can produce output that you might not need. For example, a command can produce output that simply notes its successful execution (i.e., standard output) or any problems encountered (i.e., error output). Such output can produce clutter and even be confusing when it appears onscreen, so suppressing that output might be desirable. You can suppress output by redirecting it to a device named NUL. You can think of NUL as the command-shell trash can. When you redirect output to NUL, the output isn't visible onscreen.

Let's first look at how to suppress a command's standard output. Suppose you want to map a drive to a share, so you type the command

Net Use * \\servername\sharename

at the command prompt, where servername is the name of the target server and sharename is the name of the target share. When you run this command, the system maps the specified drive to the specified share, then sends the standard output The command completed successfully to your screen. If you don't want to clutter your screen with that output, you can suppress it by appending > NUL to the Net Use command:

Net Use * \\servername\sharename > NUL

When you run this command, the system sends the standard output to the command-shell trash can instead of your screen.

Now let's look at how to suppress a command's error output. Let’s intentionally force an error by trying to map a drive to a share that doesn't exist. At the command prompt, type

Net Use R: \\servername\noshare

where servername is the name of your server and noshare is a fictitious share. When you run this command, your screen will display error output that reads something like System error 67 has occurred. The network name cannot be found. To suppress that error output, you can append 2> NUL to the command:

Net Use R: \\servername\noshare 2> NUL

When you run this command, the system redirects the error output to the command-shell trash can.

For More Examples of Redirection in Action
The 20530.zip file contains another script, BootIniTester.bat, that provides more examples of how redirection symbols work. This script tests the C and D drives on your machine to see whether the boot.ini file is present, then creates a report detailing the results.

Homework Assignments

  1. Use HelloWorld.bat as a template to create a script that displays the values of several more environment variables.
  2. Run a command that you know will fail, such as
  3. Copy C:\fred47.txt D:\fred.txt >NUL

    Remove >NUL, and run the command again. Compare the output of the two commands to see the difference.

End of Article



Reader Comments
I have been getting good information from this site thanks to the one who does this

Anonymous User October 28, 2004 (Article Rating: )


I have been getting good information from this site thanks to the one who does this

Anonymous User October 28, 2004 (Article Rating: )


great! thanks a lot for this information!

Anonymous User November 08, 2004 (Article Rating: )


This is real what i searched for.

Anonymous User December 15, 2004 (Article Rating: )


perfect and precise

Anonymous User May 22, 2005 (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
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. ...

Microsoft, News Corp. Discuss Locking Out Google

Microsoft and Rupert Murdoch's News Corp. recently discussed an alliance that would counter Google's fledgling online news service. ...

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 9

Shell Scripting 101, Lesson 8

Shell Scripting 101, Lesson 8

Scripting Whitepapers 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!

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