Operators
Note
Redirection,
|and&are thin wrappers around kernel syscalls (e.g.,|=pipe()).&&,||and;are not, they are pure shell control flow, branching on an exit status.
Redirection and pipes
Shell
< # connects the STDIN to contents of an existing file
> # redirects STDOUT, replaces file's existing contents
>> # redirects STDOUT, appends to a file
0<, 1>, 2> # specifically target where from and to send STDIN, STDOUT, STDERR
2>&1 # point fd2 to where fd1 is pointing, the & says this is a fd not a file
1>/dev/null 2>&1 # send fd1 to /dev/null and send fd2 to where fd1 is pointing
| # connect fd1 of of one process to fd0 of the next via kernel pipe()
>& # not POSIX: >&file redirects both STDOUT and STDERR
>& /dev/null # updates fd1 and 2 (stdout and stderr) at the same timeExamples
Shell
find / -name core 2> /dev/null # redirect STDERR to null driver
find / -name core 1> ~/results.txt 2>/dev/null # redirect STDOUT
# Using tee, (origin is from plumbing T which split in two directions)
# it reads STDIN, writes to STDOUT and also the named file
find / -name core 2> /dev/null | tee ~/results.txtControl operators
Shell
x && y # only do Y if X passes (return 0)
x || y # only do Y if X fails (return != 0)
& # If a command is terminated &, the shell executes the command in the background in a subshell
; # split a single line into multiple commands
# Not an operator, an convience escape char, joins lines since shells only accept single lines
# To use, type a '\' and press enter to go to the next line
\ # combine multiple lines into a single commandExamples
Shell
cd foo || echo "No such directory"Extra Examples
Redirect errors and run in background
Shell
# 1> - updates pointer for fd1 from (say) /dev/pts/0 (terminal) to /dev/null,
# nothing is closed or open the data structure is just updated
# 2>&1 - copy fd1's target (file descriptor) into fd2's slot (not a reference)
# & - finally run in background
hugo server 1>/dev/null 2>&1 &
# You can also do 1> implicitly as mentioned above with just >