Labs ICT
โญ Pro Login

Redirection

The terminal has a standard way of handling input and output. Every command has a source for input (usually the keyboard, called stdin) and two outputs: normal output (called stdout) and error output (called stderr). Redirection lets you control where those go.

Redirect output with >

The > operator takes the output of a command and writes it to a file. If the file already exists, it gets overwritten. Be careful โ€” there is no undo button.

$ echo "Hello, world!" > hello.txt
$ cat hello.txt
Hello, world!
Try it Yourself โ†’

Append with >>

Use >> instead of > when you want to add to the end of a file without wiping what is already there. Perfect for log files, journals, or building up a list over time.

$ echo "line one" > log.txt
$ echo "line two" >> log.txt
$ cat log.txt
line one
line two
Try it Yourself โ†’

Redirect input with <

The < operator feeds the contents of a file as input to a command. It is less common than output redirection since most commands accept a filename directly, but it is useful in scripts and with commands that only read from stdin.

$ sort < names.txt
Alice
Bob
Charlie
Try it Yourself โ†’

Redirect errors with 2>

Regular output goes to file descriptor 1 (stdout). Errors go to file descriptor 2 (stderr). You can redirect them separately. 2> redirects errors while keeping normal output visible.

$ ls existing.txt missing.txt 2> errors.txt
existing.txt
$ cat errors.txt
ls: cannot access 'missing.txt': No such file or directory

If you want to throw errors away entirely, redirect them to /dev/null โ€” the special file that acts like a black hole.

$ ls existing.txt missing.txt 2> /dev/null
existing.txt
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which operator redirects standard output to a file, appending instead of overwriting?