- Published on
Basic Terminal Commands: cat, echo, and tail
- Authors
- Name
- Hieu Cao
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.
cat
Command: Concatenate and View Files
The 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
View File Contents
cat file.txt
- Displays the entire content of
file.txt
.
- Displays the entire content of
Combine Multiple Files
cat file1.txt file2.txt > combined.txt
- Merges the contents of
file1.txt
andfile2.txt
intocombined.txt
.
- Merges the contents of
Number Lines in Output
cat -n file.txt
- Adds line numbers to each line of the output.
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.
echo
Command: Print Text to Terminal
The The echo
command prints text or variables to the terminal and is often used in scripts.
Syntax
echo [options] [text]
Common Usage
Print a Simple Message
echo "Hello, World"
- Prints
Hello, World
to the terminal.
- Prints
Display Environment Variables
echo $HOME
- Prints the value of the
HOME
environment variable.
- Prints the value of the
Redirect Output to a File
echo "This is a log entry." >> log.txt
- Appends the text to
log.txt
.
- Appends the text to
Enable Escape Characters
echo -e "Line1\nLine2"
- Prints with a newline character between
Line1
andLine2
.
- Prints with a newline character between
tail
Command: View End of Files
The 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
View Last 10 Lines of a File
tail file.txt
- Displays the last 10 lines of
file.txt
.
- Displays the last 10 lines of
Specify Number of Lines
tail -n 5 file.txt
- Displays the last 5 lines of
file.txt
.
- Displays the last 5 lines of
Monitor File Changes in Real-Time
tail -f log.txt
- Continuously displays new lines added to
log.txt
.
- Continuously displays new lines added to
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:
Create a File and Add Content
echo "First line" > example.txt echo "Second line" >> example.txt
View the File Content
cat example.txt
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!