8.6 Output Command-Line ArgumentsThe echo command writes its command-line arguments and a newline to the standard output. Shell scripts use echo for sending text to the terminal, down a pipe, and into a file. You can use echo on the command line to show the value of a variable (6.1 , 6.8 ) , to see how filename wildcards will expand without doing anything else to those files, or to check quoting (46.2 ) : % The printf command gives you more formatting control. 8.6.1 PortabilityThe C shell and most other newer shells have a version of echo that's built in (1.10 ) so it's faster. The original echo , and the csh echo which acts like it, have just one option. The -n option tells echo not to print a newline after the message. Shell scripts use -n to send a question to a user and leave the cursor at the end of the message: echo -n "Enter your name: " (The space at the end makes the prompt look better. The quotes make the shell pass that space on to echo .)
Newer versions of echo
check their arguments for a backslash ( $ In this version of echo
, a echo "Enter your name: \c" Your online echo (or csh ) manual page should tell you which version you have and list any escape sequences. The problem with this newer echo is that it's tough to echo an arbitrary string that might have a backslash in it. Chris Torek has a workaround: use a here-document (8.18 ) and cat (25.2 ) instead of echo . For example: cat << END The answer is: $ bash users are lucky: That shell's echo has a -e option that enables backslash interpretation, and a -E option that disables it.
$ Because printf isn't built into any shells I know of, it's more portable than the crazy set of echo s. If we had printf and the old echo , life would be easier. Article 46.10 shows a way to make echo portable. The C shell echo works differently from other versions. For example, to make an empty line with the standard echo , don't give any arguments. (This is usually done for readability - to put blank lines between other output.) Standard echo will just print a newline: $ Without arguments, the C shell echo doesn't print the newline. To get a newline, you have to give an empty argument: % To use the standard echo from the C shell, type /bin/echo instead. 8.6.2 Making Error Messages
echo
writes to standard output.
Error messages in shell scripts should be written to the standard error
so that
redirection (13.1
)
of standard output doesn't accidentally capture the message.
The Bourne shell
echo "progname: choke wheeze complain" 1>&2 The C shell can't do that - which is another reason not to write shell scripts with csh (47.2 ) . - |
|