Writing Output Without the Newline
Problem
You want to produce some output without the default newline that echo provides.
Solution
Using printf it’s easy—just leave off the
ending \n
in your format string. With
echo, use the -n
option.
$ printf "%s %s" next prompt next prompt$
or:
$ echo -n prompt prompt$
Discussion
Since there was no newline at the end of the printf format string (the first argument), the prompt character ($) appears right where the printf left off. This feature is much more useful in shell scripts where you may want to do partial output across several statements before completing the line, or where you want to display a prompt to the user before reading input.
With the echo command there are two ways to eliminate the newline. First, the -n
option suppresses the trailing newline. The echo
command also has several escape sequences with special meanings similar to those in
C language strings (e.g., \n
for
newline). To use these escape sequences, you must invoke
echo with the -e
option. One of echo’s escape sequences is \c
, which
doesn’t print a character, but rather inhibits printing the ending
newline. Thus, here’s a third solution:
$ echo -e 'hi\c' hi$
Because of the powerful and flexible formatting that printf provides, and because it is a built-in with very little over head to invoke (unlike other shells or older versions of bash, where printf was a standalone executable), we will use printf for many of our examples throughout the book.
See Also
help echo
help printf
http://www.opengroup.org/onlinepubs/009695399/functions/printf.html ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.