Using echo and printf
Scripts need to talk: they print messages, results and error text. Bash has two built-in commands for this, echo and printf. The echo command is quick and simple. The printf command is more precise: it can align columns, pad numbers, format decimals and print the same text on every system. This lesson explains both, shows where echo surprises people, and helps you decide which to use.
Understanding the Concept
Both commands write text to standard output, the stream that normally appears in your terminal, and both are Bash built-ins. You can confirm that:
type echo printf
echo is a shell builtin
printf is a shell builtin
The difference is how they treat their arguments:
echoprints its arguments separated by single spaces, then adds a newline. It has a few options, and its handling of backslash sequences varies between shells.printftakes a format string first and then values. The format controls the layout, the way theprintffunction does in C. It prints exactly what the format says, and it adds a newline only if the format contains one.
The echo Command
The simplest use prints the words you give it:
echo Hello, Bash
Hello, Bash
Quoting and Spaces
Bash splits an unquoted command line into words, and echo prints those words with one space between them. Extra spaces are lost:
echo "Hello, Bash"
echo Hello, Bash
Hello, Bash
Hello, Bash
In the first line the quotes make one argument, so the three spaces stay. In the second line, echo received two separate arguments, Hello, and Bash. The same effect applies to variables, which is why variables should usually be in double quotes:
msg=" spaced text "
echo $msg
echo "$msg"
spaced text
spaced text
Quotes and Special Characters
Inside single quotes nothing is replaced. Inside double quotes variables and commands are replaced:
echo 'single $HOME'
echo "double $HOME"
single $HOME
double /home/suriya
An unquoted * is expanded by Bash into the names of the files in the directory, before echo sees it:
echo *
echo "*"
With two files named one.txt and two.txt present:
one.txt two.txt
*
Printing a Blank Line
echo with no arguments prints an empty line:
echo "before"
echo
echo "after"
before
after
The -n Option: No Newline
By default, echo ends its output with a newline. The -n option suppresses it, so the next output continues on the same line:
echo -n "no newline"
echo "<- same line"
no newline<- same line
This is useful for prompts, where the cursor should stay right after the text.
The -e Option: Backslash Escapes
By default, Bash's echo prints backslashes literally. With -e, it interprets escape sequences:
echo "Line1\nLine2"
echo -e "Line1\nLine2"
Line1\nLine2
Line1
Line2
The common sequences are:
| Sequence | Meaning |
|---|---|
\n | New line |
\t | Tab |
|