Published on

Basic Terminal Commands: cat, echo, and tail

Authors
  • avatar
    Name
    Hieu Cao
    Twitter

Introduction

The terminal is a versatile tool for working with text files and output. Three fundamental commands—cat, echo, and tail—enable users to view, create, and inspect text content efficiently. This guide introduces these commands, their common options, and practical applications.

The cat Command: Concatenate and View Files

The cat command allows you to display the contents of files, combine multiple files, or create new files.

Syntax

cat [options] [file_name]

Common Usage

  1. View File Contents

    cat file.txt
    
    • Displays the entire content of file.txt.
  2. Combine Multiple Files

    cat file1.txt file2.txt > combined.txt
    
    • Merges the contents of file1.txt and file2.txt into combined.txt.
  3. Number Lines in Output

    cat -n file.txt
    
    • Adds line numbers to each line of the output.
  4. Create a File

    cat > new_file.txt
    This is a new file.
    Press Ctrl+D to save.
    
    • Creates a new file and adds content to it.

The echo Command: Print Text to Terminal

The echo command prints text or variables to the terminal and is often used in scripts.

Syntax

echo [options] [text]

Common Usage

  1. Print a Simple Message

    echo "Hello, World"
    
    • Prints Hello, World to the terminal.
  2. Display Environment Variables

    echo $HOME
    
    • Prints the value of the HOME environment variable.
  3. Redirect Output to a File

    echo "This is a log entry." >> log.txt
    
    • Appends the text to log.txt.
  4. Enable Escape Characters

    echo -e "Line1\nLine2"
    
    • Prints with a newline character between Line1 and Line2.

The tail Command: View End of Files

The tail command displays the last few lines of a file. It is especially useful for monitoring logs.

Syntax

tail [options] [file_name]

Common Usage

  1. View Last 10 Lines of a File

    tail file.txt
    
    • Displays the last 10 lines of file.txt.
  2. Specify Number of Lines

    tail -n 5 file.txt
    
    • Displays the last 5 lines of file.txt.
  3. Monitor File Changes in Real-Time

    tail -f log.txt
    
    • Continuously displays new lines added to log.txt.

Example

tail -f /var/log/syslog
  • Monitors the system log for new entries in real-time.

Practical Example

Let’s demonstrate these commands in a typical workflow:

  1. Create a File and Add Content

    echo "First line" > example.txt
    echo "Second line" >> example.txt
    
  2. View the File Content

    cat example.txt
    
  3. Monitor File Updates

    tail -f example.txt
    

Conclusion

Understanding and using cat, echo, and tail commands is crucial for efficient file handling and debugging in the terminal. These commands are easy to learn and form the backbone of many everyday tasks in Linux and macOS environments. Practice these commands to enhance your terminal skills and productivity!