Episode Details
Back to EpisodesHPR4667: UNIX Curio #9 - printf
Description
This show has been flagged as Clean by the host.
This series is dedicated to exploring little-known—and occasionally useful—trinkets lurking in the dusty corners of UNIX-like operating systems.
The
echo
command is very useful—it prints the arguments given to it, followed by a newline character. (The newline is sometimes also called a linefeed character depending on who is writing or speaking, and has the ASCII decimal value 10.) It has many uses, either in a script or interactively on the command line. The
echo
utility is used to display text, the value of a variable, or the result of a pathname expansion. It can also feed text to another command in a pipeline.
As useful as
echo
is, it should come as no surprise that it
first appeared early on in Bell Laboratories' Second Edition UNIX
1
in 1972. This
initial version accepted no options
2
—although the manual page doesn't explicitly say output is followed by a newline character, the description of writing "as a line" seems to imply it. In
Seventh Edition UNIX, the manual page
3
makes that clear, and also features the addition of the
-n
option, which causes
echo
to print the arguments
without
a trailing newline character.
Eighth Edition UNIX's
echo
4
gained the
-e
option, which allows certain escape codes from the C programming language to be used.
These variations caused differences in behavior between different versions of
echo
. Will running
echo -n something
on your system output the text "something" without a newline, or "-n something" followed by a newline? Things get even trickier when the command arguments include parameter or pathname expansions. If there are files named "-n" and "something" in the current directory, what does
echo *
output? Like the previous question, that depends on whether or not your version of
echo
treats
-n
as an option. You can't get around this ambiguity by quoting or escaping the "*", because that just causes
echo
to print a literal asterisk.
Example using GNU utilities on Debian 12; both the "echo" utility and the "echo" builtin of bash recognize "-n" as an option.
$ ls -1 -n something $ echo * something$ #Shell prompt is on the same line because "-n" was treated as an option to echo $ echo "*" *
The solution was to create a new utility, which is the first UNIX Curio for today:
printf
. This command allows a user to print text similar to the way the identically-named function works in the C programming language. You
run
printf
5
followed by a format string, followed by zero or more arguments. No newline characters are printed unless specifically indicated by the format string or the arguments.
To use
printf
to print "something" without a newline, that would just be
printf something
. This demonstrates t