Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Pipes and Redirection in Linux

1. Introduction

Pipes and redirection are fundamental concepts in Linux system administration and shell scripting. They enable users to manipulate and control the flow of data between commands and files seamlessly.

2. Pipes

A pipe allows the output of one command to be used as the input to another command. This is done using the pipe operator |.

Note: Pipes can chain multiple commands together, creating complex command lines.

2.1 Basic Syntax

command1 | command2

2.2 Example

To list all files in a directory and filter the output with grep:

ls -l | grep ".txt"

3. Redirection

Redirection allows you to change where the output of a command goes or to change where a command gets its input. The most common operators are:

  • Output Redirection: > (overwrites) and > (appends)
  • Input Redirection: <

3.1 Example

To redirect the output of a command to a file:

echo "Hello World" > hello.txt

To append to a file:

echo "Hello Again" >> hello.txt

To read from a file:

cat < hello.txt

4. Examples

4.1 Combining Pipes and Redirection

You can combine pipes and redirection to create powerful command sequences. For example:

ps aux | grep "httpd" > httpd_processes.txt

5. Best Practices

  • Always check your commands without redirection first to avoid data loss.
  • Use tee to view output and write to a file simultaneously.
  • Be cautious when using output redirection to overwrite files.

6. FAQ

What happens if I use > on a non-existent file?

The file will be created, and the command's output will be written to it.

Can I use multiple pipes in a single command?

Yes, you can chain multiple commands together using pipes.

What is the difference between > and >>?

> overwrites the file, while >> appends to it.