Shell Script · I/O Redirection

Shell Scripting · Lesson 19

I/O Redirection

Input output redirection in Linux shell. Use > >> and pipes. Redirect errors and logs. Important concept for automation.

What is I/O Redirection?

I/O redirection allows you to control where input comes from and where output goes. By default, commands read from keyboard and write to terminal.

Types of Redirection

  • Standard Input (stdin) – 0
  • Standard Output (stdout) – 1
  • Standard Error (stderr) – 2

Redirection Examples

1. Standard Output Redirection ( > )

Redirect command output to a file (overwrite).

terminal — bash
io
echo "Hello World" > output.txt
cat output.txt

2. Append Output ( >> )

Append output to an existing file.

terminal — bash
io
echo "Line 1" > file.txt
echo "Line 2" >> file.txt
cat file.txt

3. Standard Error Redirection (2>)

Redirect error messages to a file.

terminal — bash
io
ls /wrongpath 2> error.log

4. Redirect Both Output and Error

Redirect both stdout and stderr.

terminal — bash
io
command > all.log 2>&1

5. Using Pipe ( | )

Send output of one command as input to another.

terminal — bash
io
ls -l | grep ".txt"

Best Practices

I/O Best Practices

  • Always redirect errors to logs.
  • Use >> instead of > to avoid data loss.
  • Use pipes to chain commands efficiently.
  • Keep logs organized and readable.

Practice Task – I/O Redirection

  • Redirect command output to a file.
  • Redirect error messages to a log file.
  • Use pipe to filter output.

Next lesson: File Permissions & Ownership