Skip to main content

Linux, Redirecting Input and Output

Linux provides powerful redirection operators to control where commands read input from and send output to, instead of using the default keyboard (stdin) and terminal (stdout).

Output Redirection

Basic Output Redirection (>)

ls -l > file_list.txt

This redirects the output of ls -l to a file called file_list.txt, creating or overwriting it.

Append Output (>>)

echo "New entry" >> file_list.txt

This appends text to the existing file without overwriting previous content.

Error Redirection (2>)

find /root -name "*.txt" 2> errors.log

This redirects error messages (stderr) to errors.log while normal output still goes to the terminal.

Redirect Both Output and Errors (&>)

command &> all_output.txt
# or alternatively
command > output.txt 2>&1

Input Redirection

Basic Input Redirection (<)

sort < unsorted_list.txt

This feeds the contents of unsorted_list.txt as input to the sort command.

Here Document (<<)

cat << EOF
This is a multi-line
input that ends when
EOF is encountered
EOF

Pipes (|)

Pipes connect the output of one command to the input of another:

ps aux | grep firefox | wc -l

This counts how many Firefox processes are running by chaining commands.

Practical Example

# Create a log file with both success and error messages
ls -l /home /invalid_path > output.log 2> error.log

# Or combine everything
ls -l /home /invalid_path &> combined.log

# Process and sort a file
cat names.txt | sort | uniq > sorted_unique_names.txt

These redirection techniques are essential for automation, logging, and creating efficient command pipelines in Linux systems.