← Back to Bash Course | Chapter 3: Control Flow | Lesson 5 of 14

Redirections (> >> 2>)

Redirection is like choosing where water from a tap goes: into a bucket (a file) instead of the sink. One arrow pours over the old water, two arrows add on top, and another arrow catches only the error messages.

In this page:

  1. Redirections (> >> 2>)
Syntax
bash
command > file      # overwrite stdout
command >> file     # append stdout
command 2> file     # redirect stderr

Redirections (> >> 2>)

> redirects standard output to a file, overwriting it; >> appends instead of overwriting. 2> redirects standard error separately from standard output, and 2>&1 merges error into the same stream as output.

Redirection is essential for logging and separating normal output from error messages.

Warning: > truncates the target file immediately, even if the command that follows fails to run.

Example: Redirections (> >> 2>)

bash
#!/bin/bash
echo "First line" > output.txt
echo "Second line" >> output.txt
cat output.txt

ls /no/such/path 2> error.txt
cat error.txt
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using > when you mean >>, which overwrites the file instead of appending.
  2. Writing 2>&1 before the redirection to the file, as in cmd 2>&1 > out, so errors still go to the terminal.
  3. Reading and writing the same file in one command, as in sort file > file, which empties it first.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.