Quantcast
Viewing all articles
Browse latest Browse all 314

How to Use the Bash echo Command, With Examples

The Bash echo command serves a simple purpose – it outputs (echos) text. Here’s how to use it, with examples.

echo Command Syntax

The echo command is very simple and has the following syntax:

echo OPTIONS TEXT

Note that:

  • OPTIONS should be one of the following options
    • -n Do not output a trailing newline
    • -e Enable interpretation of backslash escapes
      • This means that escape characters can be used to insert special characters into the output
        • \\ backslash
        • \a alert (BEL)
        • \b backspace
        • \c produce no further output
        • \e escape
        • \f form feed
        • \n new line
        • \r carriage return
        • \t horizontal tab
        • \v vertical tab
  • TEXT is the text to be echoed/printed/output
  • The echo command will then output the given TEXT to STDOUT

echo Bash Command Examples

The simplest usage of echo is to print some text:

echo Hello LinuxScrew!

…which will result in the following output to the console:

Hello LinuxScrew!

You can also echo the value of variables

message="Buy more oranges!"
echo $message

Which will of course output:

Buy more oranges!

The true power of the echo command is when it is used with redirection (STDOUT/STDIN) which lets you redirect the output of the echo command into text files and other command line programs:

echo "This text will be written to a file" > file.txt

The above command uses redirection (>) to send the output of the echo command to the file file.txtIt will overwrite the contents of an existing file, so be careful!

echo "This text will be appended to a file" >> file.txt

If you want to append the text to a file instead of overwriting it, the above code demonstrates how the >> command is used to append the redirected output.

You can use pipes (|) as well to send the output of echo directly to another command line program:

echo "/path/to/folder" | ls

Above, a path is provided as a string to the echo command, which then pipes it (using the | command) to the ls program, which then lists the content of the directory.

View the original article from LinuxScrew here: How to Use the Bash echo Command, With Examples


Viewing all articles
Browse latest Browse all 314

Trending Articles