#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:
$ echo "Hello" > greeting.txt
$ cat greeting.txt
HelloThis 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:
$ 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:
$ wc -l < notes.txt
3The 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):
$ 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 &&:
$ ls missing-file || echo "Not found"
ls: missing-file: No such file or directory
Not foundThis is useful for providing fallback behavior.
; -- Execute regardless
The semicolon ; executes the next command regardless of the result of the previous one:
$ echo "one" ; echo "two"
one
twoSummary
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 regardlessYour turn
Try the redirections and chaining operators in the terminal below. Create a file with >, append content with >>, then verify with cat.