$ echo $?
Status | Description |
---|---|
0 |
Sucessful |
1 |
General error |
2 |
Misuse of shell builtins |
126 |
Command invoked cannot execute |
127 |
Command not found |
128 |
Invalid argument to exit |
Operator | Description |
---|---|
&& |
Run if preceding command exited with 0 |
` | |
; |
Run unconditionally |
` | ` |
& |
Run both commands in paralell, the first in background and second in foreground. |
>, <, >> |
Redirect the output of a command or a group of commands to a stream or file. |
You can use redirection operators >, <, >>
to redirect either the standard input, standard output or both.
$ sort < inputfile.txt
Sort the contents of the file, named inputfile.txt
. It will print out the sorted content into the standard output or the screen.
$ ls -l /path/ > ~/temp/filelist.txt
Save the output of the ls command into a file name filelist.txt
. It is useful in couple of different scenarios: if you want to view the output at a later time or if the output is too long to fit into a screenful or so.
>>
works exactly like the >
operator but will append the output to the file rather than overwriting the output file stream.
$ sort < inputfile.txt > outputfile.txt
You can use both the input and output redirection operators together in the command. The above sort command will take the contents of inputfile.txt
, sort them and then save them as outputfile.txt
.
File Descriptor | Symbol | Description |
---|---|---|
0 |
stdin | Standard input stream |
1 |
stdout | Standard output stream |
2 |
stderr | Standard error stream |
By default, all I/O streams output to the device of the standard console, usually the screen.
$ echo test 1> capture.txt
$ cat capture.txt
test
$ cat missing.txt 2> capture.txt
$ cat capture.txt
cat: missing.txt: No such file or directory
cat missing.txt > capture.txt 2>&1
Redirecting output >
without a file descriptor implies usage of I/O stream of 1
(stdout).
2>&1
will take I/O stream of 2
(stderr), redirect it to the same destination of I/O stream 1
(stdout).
The file /dev/null
is discarded.
$cat missing.txt >/dev/null 2>&1
The above command will silently throw away I/O streams 1
(stdout) and 2
(stderr).