What it does
echo writes its arguments, separated by spaces, followed by a new line. It is the simplest way to show a variable, write a line to a file, or print a message in a script.
Bash has echo built in; there is also a program /usr/bin/echo from coreutils. They work the same for normal use.
For exact formatting (numbers, tabs, no surprises with backslashes), printf is the safer tool.
How to write it
echo [-neE] [TEXT ...]Options 13
Most used
Backslash codes (with -e)
Nothing matches this filter.
Examples 12
$ run as a normal user# run as root (or with sudo)
1Print a message
echo "Backup started" Backup startedQuotes keep the spaces as they are.
2Show the value of a variable
echo "$HOME" /home/studentAlways put variables in double quotes, so spaces in the value do not break the line.
3Write a line to a file
echo "192.168.122.20 server2.example.com server2" >> /etc/hosts>>adds the line at the end. With>the file would be emptied first.4Write to a file that needs root, from a normal user
sudo echo ... > filedoes not work, because the redirect runs as your user.teeruns with sudo.5Print several lines with -e
echo -e "line one\nline two\ttab"\nmakes a new line and\ta tab.6Print without a new line (for a prompt)
echo -n "Enter the server name: "; read SERVERThe cursor stays on the same line.
7Show the exit code of the last command
grep -q root /etc/passwd; echo $? 00 means success. Any other number means an error.
8Print colored text in a script
echo -e "\e[31mERROR\e[0m disk is full"\e[31m= red,\e[0m= back to normal. Good for warnings in deploy scripts.9Make a quick test file
echo "hello" > /tmp/test.txtUseful to test permissions, SELinux labels or a web server.
10Show the PATH, one folder per line
echo "$PATH" | tr ':' '\n'Easier to read than one long line.
11Check a variable inside a script while you debug
echo "DEBUG: user=$USER host=$(hostname) dir=$PWD" >&2>&2sends the message to the error channel, so it does not mix with the normal output.12Use brace expansion to see what it makes
echo web{01..03}.example.com web01.example.com web02.example.com web03.example.comBash expands the braces before echo runs. Good to test a pattern before you use it.
Nothing matches this filter.
Watch out
sudo echo text > /root/filefails: the redirect is done by your shell, not by sudo. Use| sudo tee.- Text that starts with
-nor-eis read as an option. Useprintf '%s\n' "$TEXT"for unknown text. - Without quotes, several spaces become one and
*is expanded to file names.
Tips to remember
echo $?= did the last command work?>= new file,>>= add to the file.