Outputting text (echo)
Outputting text can be conveniently done using the echo command, which is available independently of the bash shell.
This is possibly the simplest command out there, but the man page is still handy.
Related topics: Redirecting Output, Quoting Arguments.
Quoting text
Aggressively quoting text to limit the shell expansions performed makes the output more predictable. See the Quoting Guidelines for more information about how to do this.
Outputting error messages
Error messages should be written to stderr- if the caller of the script redirects the expected output into another script/command, curious behaviour could result when an error occurs:
echo "File not found: ${file}" >&2
Explicitly outputting newlines ( -e)
By default, echo performs no special processing of the input. Hence, \n will be passed through:
> echo "\n" \n > _
Use the -e option to embed newlines ( \n) in the output. It enables backslash escape interpretation (which includes quite a lot more than just newlines - see the man page for more info):
> echo -e "Hello,\nWorld!" Hello, World! > _
Suppressing the trailing newline ( -n)
By default, echo will append a newline to the output. Use the -n option to suppress the trailing newline:
# Will output "Deleting files... OK" with a trailing newline echo -n "Deleting files..." # delete files... echo " OK"
Suppressing trailing newlines does not enable processing of \n:
> echo -n "\n" \n > _
Combine -e and -n for complete newline control:
> echo -en "x\nx" x x> _
Multi-line output ("here documents")
Multi-line output can be quite unreadable using multiple echo-es:
echo " <entry>" echo " <title>${title}</title>" echo " </entry>"
Here documents, and the cat command ( man page), provide an elegant solution:
cat <<mydelimiter <entry> <title>${title}</title> </entry> mydelimiter
Note that:
- mydelimiter can be any word of your choosing - it should not occur on a line by itself in the document contents, since this terminates the here document.
- Whether quoted or not, no shell expansions are performed on the delimiter.
- If the chosen delimiter is quoted, no shell expansions are
performed on the document contents, so changing the first line to:
cat <<"mydelimiter"
will leave ${title} verbatim in the output. - If the delimiter is unquoted, parameter expansion, command substitution, and arithmetic expansion are performed on the document contents.
See also: The GNU bash manual: 3.6.6 Here Documents.