Skip to content

Instantly share code, notes, and snippets.

@keilmillerjr
Last active October 10, 2020 07:30
Show Gist options
  • Save keilmillerjr/0ec2ad5553a37b957494e9b15a3d16d1 to your computer and use it in GitHub Desktop.
Save keilmillerjr/0ec2ad5553a37b957494e9b15a3d16d1 to your computer and use it in GitHub Desktop.
Bash

Bash

Exit Status

$ 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

Chaining Operators

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.

Redirection

You can use redirection operators >, <, >> to redirect either the standard input, standard output or both.

Input

$ 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.

Output

$ 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.

Append Output

>> works exactly like the > operator but will append the output to the file rather than overwriting the output file stream.

Input and Output

$ 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.

I/O Streams

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.

Redirecting stdout

$ echo test 1> capture.txt
$ cat capture.txt
test

Redirecting stderr

$ cat missing.txt 2> capture.txt
$ cat capture.txt
cat: missing.txt: No such file or directory

Redirecting stdout and stderr To The Same File

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).

Silently Throw Away I/O Stream

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment