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:
Syntax
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>)
#!/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
Login to try C/C++/Java/PHP code in the editor
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
- Using
>when you mean>>, which overwrites the file instead of appending. - Writing
2>&1before the redirection to the file, as incmd 2>&1 > out, so errors still go to the terminal. - Reading and writing the same file in one command, as in
sort file > file, which empties it first.
🔒
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: