Linux operators: Using |, >, >>, &, &&, !, =, () and many more
In the example below, the head command fails because it wasn’t run with root-level privilege (e.g., using sudo) and, thus, has no access to the /etc/shadow file. The echo command then runs after the error appears.
$ head -4 /etc/shadow || echo oops head: cannot open '/etc/shadow' for reading: Permission denied oops
If you want to see the effect without the error message, you could send the error output of the head command to /dev/null like this:
$ head -4 /etc/shadow 2>/dev/null || echo oops oops
The 2> operator redirects error output – in this case to /dev/null.
Using > and >>
The > and >> operators, unlike | and ||, are tightly related to each other. Still, they have a different though related function. If you run a command like one of those below, you add output of the fortune command to a file, creating it if is doesn’t already exist and overwriting it if it does.
$ fortune > readme $ cat readme 1 bulls, 3 cows. $ fortune > readme $ cat readme Does a one-legged duck swim in a circle?
Notice that, in the example above, the content of the file is replaced.
If you use >> instead, content will be appended to the file if it exists and used to create a new file if it doesn’t.