The echo command is one of the most used shell built-in command, and as you have probably guessed, it is used to print a line of text to standard output (the screen). It sends a copy of an input signal (your keyboard) or string for display.
In this guide, we would look at echo and its option you can use in your shell.
This is echo syntax:
echo [option]… [string]…
You can pass an option to a string, before we go into the nitty gritty, simply enter echo without any option or string at your shell prompt:
user@server:~/$ echo
user@server:~/$
The output will show a clear new line between the command we issued as you can see above. If you want to suppress this, perhaps in a situation where you are prompting users, you can use the following:
echo -n "Which file should I back up ?: "
It would print something like this if you are using it directly at the shell prompt:
Which file should I back up ?: user@server:/$
The -n option means, do not output the trailing newline, but as you can see it doesn't look cool when used directly in a command shell, don't worry, if you are using it in a script, it does what you would expect.
If you are not using it in a script, you can do something like this:
echo -n "Which file should I back up ?: "; echo
There is an -e option, which enable interpretation of the backslash-escaped characters in each string, these are the following backslash-escaped characters you can use with the -e option:
- ‘\a’ - alert (bell)
- ‘\b’ - backspace
- ‘\c’ - produce no further output
- ‘\e’ - escape
- ‘\f’ - form feed
- ‘\n’ - newline
- ‘\r’ - carriage return
- ‘\t’ - horizontal tab
- ‘\v’ - vertical tab
- ‘\\’ - backslash
Let's see some example:
Using option ‘\b‘ – backspace with backslash interpretor ‘-e‘ to remove spaces
echo -e "Remove \bThe \bDamn \bSpace"
RemoveTheDamnSpace
Using option '\c' to suppress line feed output with backslash interpretor ‘-e‘
echo -e "Remove The LineFeed \c"
Remove The LineFeed user@blog:/$
This looks a bit messy, and this is due to the fact that we are using it directly at the shell prompt, use something like this to get a clean ouput:
echo -e "Remove The LineFeed \c"; echo
Remove The LineFeed
user@blog:/$
Using option '\n' to print a new line with backslash interpretor ‘-e‘
user@server:/$ echo -e "Print \nNew \nLine \nFor \nof \nEach \nWord"
Print
New
Line
For
of
Each
Word
user@server:/$
Using option ‘\t‘ – horizontal tab with backslash interpretor ‘-e‘ For horizontal tab spaces
user@server:/$ echo -e "Print \tAn \tHorizontal \tTab \tSpaces"
Print An Horizontal Tab Spaces
Using option ‘\v‘ – horizontal tab with backslash interpretor ‘-e‘ For Vertical tab spaces.
user@server:/$ echo -e "Print \vA \vVertical \vTab \vSpaces"
Print
A
Vertical
Tab
Spaces
Experiment and enjoy yourself.