Phase 2Master bash

#7 Redirections and chaining

>, >>, &&, ||

> -- Redirect output (overwrite)

The > operator redirects the output of a command to a file. If the file already exists, its content is replaced:

Redirect with overwrite
$ echo "Hello" > greeting.txt
$ cat greeting.txt
Hello

This is a simple way to create a file with content in a single command.

>> -- Redirect by appending

The >> operator appends the output to the end of the file without overwriting the existing content:

Redirect with append
$ echo "Hello" > greeting.txt
$ echo "Goodbye" >> greeting.txt
$ cat greeting.txt
Hello
Goodbye

< -- Redirect input

The < operator sends the content of a file as input to a command:

Input redirection
$ wc -l < notes.txt
3

The difference with wc -l notes.txt is subtle: with <, the command does not know the file name, it just receives its content.

&& -- Execute on success

The && operator executes the next command only if the previous one succeeded (exit code 0):

Chain on success
$ mkdir project && cd project && echo "OK"
OK
# All 3 commands succeeded

$ ls missing-file && echo "Found"
ls: missing-file: No such file or directory
# echo is not executed because ls failed

|| -- Execute on failure

The || operator executes the next command only if the previous one failed. It is the opposite of &&:

Chain on failure
$ ls missing-file || echo "Not found"
ls: missing-file: No such file or directory
Not found

This is useful for providing fallback behavior.

; -- Execute regardless

The semicolon ; executes the next command regardless of the result of the previous one:

Always chain
$ echo "one" ; echo "two"
one
two

Summary

Summary
command > file        # Redirect (overwrite)
command >> file       # Redirect (append)
command < file        # Input from a file
cmd1 && cmd2          # cmd2 if cmd1 succeeds
cmd1 || cmd2          # cmd2 if cmd1 fails
cmd1 ; cmd2           # cmd2 regardless

Your turn

Try the redirections and chaining operators in the terminal below. Create a file with >, append content with >>, then verify with cat.

terminal — bash
user@stemlegacy:~$