View and vote on the article here: Shell Programming Series(II)
Shell Programming Series(II)| Category | | | Summary | Printf
The previous program [Shell Programming Series (I)] could also have been written using printf instead of echo. The printf command performs a similar function, but allows more control over how its output is formatted. The following example |
| | Body | 1.#!/bin/sh
2.
3.# The legendary Hello World program
4.# As implemented in the Bourne shell programming language.
5.
6.printf ? Hello World! ?
7.exit 0
The backslash is an escape character that means the character immediately following it has special meaning. In this case, the ?n? is a newline character. This is why we could eliminate the two echo commands to insert blank lines when we use printf. Because now we can embed the newlines directly into the string we wish to print. At the end of the string, we used two newline characters because printf does not automatically insert a newline at the end. So, we want two newlines to get a blank line.
Following is an example in which printf doesn't automatically insert a blank line at the end:
printf ?Hello ?
printf ?World! ?
The previous two lines in a shell script would produce the output ?Hello World!?, even though they are separate statements. This is because printf doesn't automatically insert a blank line at the end of a statement. If we had used echo in the previous two lines instead of printf, ?Hello? and ?World!? would be on separate lines.
The printf command supports the following formatting characters (using backslash before each of them):
a --Ring the terminal's bell. In the old Teletype days, this rang an actual bell on the teletype machine. These days, it usually beeps the computer's speaker.
[/i]
b --Print a backspace character.
f --Print a form-feed character.
[i]n--Print a newline character.
r--Print a carriage return. The difference between this and the newline character is that the carriage return returns the cursor to the beginning of the line, but does not send to the next line. The result is that the previous output on the line will be overwritten by whatever comes after the character.
t--Print a tab character.
v --Print a vertical tab character.
' --Print a single-quote character.
? --Print a double-quote character.
[/b]
[backslash]<STRONG>--</STRONG>Print a backslash.
num [b]--Print the ASCII value of the octal 1-, 2-, or 3-bit value num. You will probably never use this feature in a shell program.
Of course, simply being able to echo messages to the screen is not very useful. This is where variables come in. So, in the next chapter we'll deal with variables.
|
|
This article was imported from zZine. (original author: ismail)
There are no replies to this post yet.
|