8 Sidestepping Poor Echo Implementations

#8 Sidestepping Poor Echo Implementations

While most modern Unix and Linux implementations have a version of the echo command that knows that the -n flag should cause the program to suppress the trailing newline, not all implementations work that way. Some use \c as a special embedded character to defeat the default behavior, and others simply insist on including the trailing newline regardless.

Figuring out whether your particular echo is well implemented is easy: Simply type in the following on the command line and see what happens:

 $ echo -n "The rain in Spain"; echo " falls mainly on the Plain" 

If your echo works with the -n flag, you'll see:

 The rain in Spain falls mainly on the Plain 

If it doesn't, you'll see this:

 -n The rain in Spain falls mainly on the Plain 

Ensuring that the script output is presented to the user as desired is quite important and will certainly become increasingly important as our scripts become more interactive.

The Code

There are as many ways to solve this quirky echo problem as there are pages in this book. One of my favorites is very succinct:

 function echon {   echo "$*"  awk '{ printf "%s" 
 function echon { echo "$*"  awk '{ printf "%s" $0 }' } 
}' }

You may prefer to avoid the overhead incurred when calling the awk command, however, and if you have a user-level command called printf you can use it instead:

 echon() {   printf "%s" "$*" } 

But what if you don't have printf and you don't want to call awk ? Then use the tr command:

 echon() {   echo "$*"  tr -d '\n' } 

This method of simply chopping out the carriage return with tr is a simple and efficient solution that should be quite portable.

Running the Script

When using this script, you can simply replace calls to echo with echon , which will leave the cursor at the end of the line, rather than automatically appending a carriage return:

 echon "Enter coordinates for satellite acquisition: " 

Wicked Cool Shell Scripts. 101 Scripts for Linux, Mac OS X, and Unix Systems
Wicked Cool Shell Scripts
ISBN: 1593270127
EAN: 2147483647
Year: 2004
Pages: 150
Authors: Dave Taylor

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net