Privacy Policy
© 2025 linux101.dev

Bash: Redirect Input and Output

Redirection allows you to change where a command's input comes from and where its output goes. This is a fundamental concept for building powerful data pipelines in Bash.

Standard Output (stdout) Redirection

Redirecting output to a file

ls > file_list.txt

The `>` operator redirects the standard output of a command to a file. If the file exists, it will be overwritten.

Appending output to a file

ls >> file_list.txt

The `>>` operator appends the output to the end of a file without overwriting its existing content.

Standard Input (stdin) Redirection

Redirecting input from a file

wc -l < file_list.txt

The `<` operator redirects the standard input of a command to come from a file. In this example, the `wc -l` (word count) command will read from `file_list.txt` instead of the keyboard.

Pipes (`|`)

A **pipe** redirects the standard output of one command to become the standard input of another. This allows you to chain multiple commands together.

Chaining commands with pipes

ls -l | grep ".sh"

This command takes the output of `ls -l` (a detailed file list) and "pipes" it to the `grep` command, which then filters the list to show only files that contain ".sh".

Standard Error (stderr) Redirection

Standard error is a separate stream for error messages. By default, it's also displayed on the screen.

Redirecting standard error

find / -name "my_file" 2> errors.txt

The `2>` operator redirects standard error to a file. This is useful for separating error messages from the command's normal output.

Redirecting all output (stdout and stderr)

find / -name "my_file" > output.txt 2>&1

This command redirects both standard output and standard error to the same file (`output.txt`). The `2>&1` means "redirect file descriptor 2 (stderr) to the same location as file descriptor 1 (stdout)."