Redirect, append and read files
A file descriptor is a numbered handle to an open input or output resource. In a normal shell, 0 is stdin, 1 stdout and 2 stderr. Bash sets up redirections before running the command body. > file opens a file for writing, creating or truncating it; >> file appends instead. < file opens an existing file for reading. n<>file opens for both reading and writing without truncation and may create a missing file; it is not append mode. The descriptor number must touch the operator. Quote variable filenames to keep them one word. An ordinary command’s redirection is temporary; the file changes are not. Use a fresh empty practice directory for every example, never a real document or an existing file you need. A pipeline (a | b) connects a producer’s stdout to a consumer’s stdin; unlike a file it is a bounded stream, and buffering may delay visible output. Pipeline status and scheduling are covered next chapter. Opening an output file is not a transaction: even if a subsequent operation fails, earlier changes remain. The examples check each file operation before reporting the result. In example 3, a failed open stops the script before writing to descriptor 3.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Append then replace
printf '%s\n' first > notes.txt || exit 1printf '%s\n' second >> notes.txt || exit 1cat notes.txt || exit 1printf '%s\n' replacement > notes.txt || exit 1cat notes.txt || exit 1Expected stdout:
firstsecondreplacementThe first cat reads two lines; the second reads only the replacement.
Read a quoted filename
file='daily report.txt'printf '%s\n' ready > "$file" || exit 1IFS= read -r line < "$file" || exit 1printf '[%s]\n' "$line" || exit 1Expected stdout:
[ready]The file supplies stdin for read, and quotes preserve the path.
Open without truncation
printf 'abc\n' > sample.txt || exit 1exec 3<>sample.txt || exit 1printf X >&3 || exit 1exec 3>&- || exit 1cat sample.txtExpected stdout:
XbcThe new descriptor starts at the beginning of the file. Writing X replaces only the first byte; exec and closure are explained later.
Common mistakes
Never redirect output to the same file a command is meant to read. Truncation can happen before the command reads anything. Avoid unquoted paths.
Practice
In a new empty directory create notes.txt with two lines using > and >>, then read them with cat. Replace its disposable contents with one line and explain why the first two disappeared.
Next: Redirect stderr and duplicate descriptors