100 Useful Command-Line Utilities

by Oliver; 2014

6. echo

echo prints the string passed to it as an argument. For example:
$ echo joe 
joe
$ echo "joe"
joe
$ echo "joe joe"
joe joe
If you leave off an argument, echo will produce a newline:
$ echo

Supress newline:
$ echo -n "joe"            # suppress newline
Interpret special characters:
$ echo -e "joe\tjoe\njoe"  # interpret special chars ( \t is tab, \n newline )
joe	joe
joe
As we've seen above, if you want to print a string with spaces, use quotes. You should also be aware of how bash treats double vs single quotes. If you use double quotes, any variable inside them will be expanded (the same as in Perl). If you use single quotes, everything is taken literally and variables are not expanded. Here's an example:
$ var=5
$ joe=hello $var
-bash: 5: command not found
That didn't work because we forgot the quotes. Let's fix it:
$ joe="hello $var"
$ echo $joe
hello 5
$ joe='hello $var'
$ echo $joe
hello $var
Sometimes, when you run a script verbosely, you want to echo commands before you execute them. A std:out log file of this type is invaluable if you want to retrace your steps later. One way of doing this is to save a command in a variable, cmd, echo it, and then pipe it into bash or sh. Your script might look like this:
cmd="ls -hl"; 
echo $cmd; 
echo $cmd | bash

<PREV   NEXT>