echo: Printing Strings or Variables in Terminal

Overview
The echo command is used to display strings or variables in the terminal.

Usage

echo [options] [args]

Description
echo is ideal for outputting text, displaying variables, and creating formatted outputs.

Options

  • -e: Enables escape characters such as newline \n and tab \t. Common escape sequences include:
    • \n: Newline
    • \t: Horizontal tab
    • \\: Backslash
    • \": Double quote
    • \a: Alert (beep)
    • \b: Backspace
    • \v: Vertical tab
  • -n: Prevents auto newline at the end of the output. By default, echo will automatically add a newline, which -n can disable.

Arguments

  • args: One or more strings or variables to be printed.

Examples

1 Simple Text Output

$ echo "Hello, World!"

Output:
Hello, World!

2 Display Variable Values
You can print variable values by prefixing the variable name with $:

$ name="Alice"
$ echo "Hello, $name"

Output:
Hello, Alice

To display environment variables:

$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

$ echo $HOME
/home/user

$ echo $USER
user

3 Using Command Substitution
echo can use command substitution with $(command) to insert the output of a command:

$ echo "Today is $(date)"

Output:
Today is Sun Oct 25 10:20:22 AM

4 Multi-line Output
Use the -e option to enable escape characters like \n for multi-line output:

$ echo -e "Line 1\nLine 2\nLine 3"

Output:

Line 1
Line 2
Line 3

5 Suppress Auto Newline
To suppress the newline, use -n:

$ echo -n "Hello, World!"

Output:
Hello, World! (without newline)

6 Using Escape Characters
Enable escape characters with -e for features like tabs (\t) and newlines (\n):

$ echo -e "Column1\tColumn2\nData1\tData2"

Output:

Column1    Column2
Data1      Data2

7 Redirect Output to File
Redirect echo output to a file. Use > to overwrite or >> to append:

$ echo "Hello, World!" > output.txt    # Overwrite
$ echo "Another Line" >> output.txt     # Append

8 Output Strings with Special Characters
For special characters (like $, “, ), use single quotes or escape them with \:

$ echo "This is a dollar sign: \$ and a quote: \""

Output:
This is a dollar sign: $ and a quote: “

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注