Pipes and text

Linux commands: echo

Learn how the Linux echo command prints its argument to the terminal, interpolates variables like $PATH, expands globs and ranges, and appends to a file.

The echo command does one simple job: it prints the argument you pass to it.

This example:

echo "hello"

prints hello to the terminal.

You will use echo all the time, both interactively and inside scripts. It’s the fastest way to see what the shell thinks a value is.

You can append the output to a file with >>:

echo "hello" >> output.txt

Run it twice and output.txt has two hello lines. With a single > the file gets overwritten instead. Be careful with that one.

You can interpolate environment variables. The shell replaces $PATH with its value before echo even runs:

echo "The path variable is $PATH"

Terminal showing echo command interpolating PATH variable displaying system directory paths

Special characters need to be escaped with a backslash \. Take $: echo The cost is $5 prints The cost is because the shell tries to expand a variable named 5, which is empty. Escape it with \$5 and you get the text you wanted:

Terminal showing echo command with and without escaped dollar sign demonstrating character escaping

This is just the start. Since the shell processes the arguments first, echo lets us play with every shell feature.

We can print the files in the current folder:

echo *

We can print only the files that start with the letter o:

echo o*

Any valid Bash (or any shell you are using) feature works here. I use echo *.md a lot to check which files a glob matches before I pass it to rm or mv.

You can print your home folder path:

echo ~

Terminal showing echo tilde command outputting the home directory path /Users/flavio

You can also execute a command and print its result to the standard output (or to a file, as you saw):

echo $(ls -al)

Terminal showing echo command executing ls -al subcommand with output displayed as single line

Notice that whitespace is not preserved by default. The whole listing gets squashed on one line. Wrap the command in double quotes to keep the newlines:

Terminal showing echo command with quoted subcommand preserving whitespace formatting in directory listing

You can generate a list of strings, for example a range of numbers:

echo {1..5}

Terminal showing echo command with brace expansion generating sequence 1 2 3 4 5 from {1..5}

This is called brace expansion. It’s handy to create many files at once, like touch chapter{1..5}.md.

The echo command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Lesson completed