Redirection
Input/Output Redirection¶
Input/output redirection is a core concept in BASH scripting that allows you to control where commands read input from and where they write output. By redirecting standard input (stdin), standard output (stdout), and standard error (stderr), you can streamline workflows, automate data processing, and debug scripts more effectively.
Standard File Descriptors¶
Unix-like systems assign three standard file descriptors to every process:
- File descriptor 0: Standard input (stdin) — used for reading input.
- File descriptor 1: Standard output (stdout) — used for normal program output.
- File, descriptor 2: Standard error (stderr) — used for error messages.
By default, stdin comes from the keyboard, stdout and stderr go to the terminal. Redirection operators override these defaults.
Output Redirection (> and >>)¶
The > and >> operators redirect stdout to files:
- **>overwrites the contents of a file or creates it if it doesn’t exist.
- **>> appends output to an existing file.
# Overwrite file.txt with "Hello, World!"
echo "Hello, World!" > file.txt
# Append "Goodbye!" to file.txt
echo "Goodbye!" >> file.txt
Note: If the target file is a directory, these operators will fail. Always ensure the destination is a file.
Input Redirection (<)¶
The < operator redirects stdin from a file:
This is equivalent to:
Pipes (|)¶
The | operator connects the stdout of one command to the stdin of another, enabling chained processing:
Pipes are ideal for processing streams of data without intermediate files.
Redirecting Multiple File Descriptors¶
You can redirect multiple file descriptors using numeric notation:
- 2> redirects stderr.
- &> redirects both stdout and stderr.
# Redirect stderr to error.log
some_command 2> error.log
# Redirect both stdout and stderr to output.log
some_command &> output.log
For advanced use cases, you can assign file descriptors to variables:
Key takeaways¶
- Use
>to overwrite files and>>to append output. - Redirect input with
<and chain commands with|for streaming data. - Redirect stderr with
2>or combine stdout/stderr with&>. - File descriptors (0, 1, 2) are fundamental for controlling I/O in scripts.
- Always verify file paths and permissions when redirecting to avoid errors.