Pcornel
Linux · Shell & Bash

Redirection

Cheat sheet · https://pcornel.dk/topic.php?topic=2685

Back to the Topic

Answer

Redirection sends a command's input or output to files: > overwrite, >> append, < input from a file, 2> stderr, 2>&1 stderr to wherever stdout goes, &> both, and here-documents with <<.

Remember

Order matters: cmd > file 2>&1 sends both to the file; cmd 2>&1 > file does not. sudo echo x > /root/f fails because the shell, not sudo, opens the file — use echo x | sudo tee /root/f. > truncates the file before the command runs.

First checks

  • bash -x script.sh — trace each expanded command
  • bash -n script.sh — syntax check only
  • shellcheck script.sh — common bugs and quoting problems
  • echo $? — exit code of the last command

Commands

sudo echo x > /root/file
sudo tee

Verify in this order

shell opens the target files left to right → file descriptors set → command runs with them

Where it usually breaks

First mismatch in persistent intent → provider/parser/generator → kernel/userspace runtime → dependency/security context → logs/counters → consumer-visible read-back; preserve identity/native diagnostic/pre-state before mutation.

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=2685

Confirmation

Confirm action

Continue?