Show Menu
Cheatography

Beginner Bash Cheat Sheet (DRAFT) by

Tips from Learning the Bash Shell by Newham and Rosenblatt

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Builtin commands

builtin
Uses builtin version of the command
cut -fnumber -ddelimiter
Displays the column specified by number
disown
Removes processes from the shell's list of jobs. Removes the job id.
eval
Re-run CL processing on arguments. Can be used to run commands passed as variables.
fg %N
Bring the job with shell ID N to the foreground
getopts
Parses positional parameters
grep -e
Regex searches for a pattern in lines in the argument files, or stdin if no files
jobs
List all jobs
printf
Prints a format string
read
Reads a line from stdin, spits it on $IFS charac­ters, and assigns it to shell variables
trap
When specified signals are received, run specified command instead and resume normal execution
type
Displays paths of argument commands, aliases, functions, execut­ables
wait
Waits for all background jobs to finish before finishing the script.

Emacs commands

CTRL-A
Move to beginning of line
CTRL-E
Move to end of line
CTRL-U
Kill backward to beginning of line
CTRL-K
Kill forward to end of line
CTRL-R
Search backward
CTRL-Y
Retrieve (yank) last killed item
ESC-B
Move one word backward
ESC-F
Move one word forward
ESC-DEL
Kill one word backward
ESC-D
Kill one word forward
ESC-<
Move to first line of history list
ESC->
Move to last line of history list

Enviro­nment files

.bash_­profile - Runs when a login shell starts.
.bashrc - Runs when a subshell starts.
.bash_­logout - Runs when a login shell exits.

Special Characters

&
Background job
#
Comment
~
Home directory
!
Logical NOT
'
Quote (strong). Skips all CL proces­sing.
"
Quote (weak). Skips all CL processing except variable expansion, command substi­tution, arithmetic substi­tution.
<
Redirect input
>
Redirect output
>>
Redirect output and append to file
|
Redirect (pipe) output to next command
/
Separator for pathname direct­ories
;
Separator for shell commands. Use when EOL is missing.
[ ]
Start and end a charac­ter-set wildcard
{ }
Start and end a command block. Redirect I/O to a block of commands without starting a subpro­cess.
( )
Start and end a subshell
(( ))
Perform arithmetic
*
Wildcard
?
Wildcard - single character
$
Variable expression
\
Escape a special character (including RETURN)

More I/O Redire­ctors

n>&m
File descriptor n is made to be a copy of output file descriptor m
n<&m
File descriptor n is made to be a copy of input file descriptor m

read builtin

-a
Read values into an array
-dD
Only read lines up to the character D
-n N
Only read the first N characters of each line
-p
Prints the string before reading input
-r
Usually backslash indicates a line contin­uation. This option interprets escaped characters like \n
-s
Do not echo the characters typed into the terminal
-t T
Wait T seconds for input, then finish

Signals

INT
Ctrl-C
TSTP
Ctrl-Z
TERM
kill
QUIT
kill -QUIT
KILL
kill -KILL
 

Variables

$0, $1, $2, ...
Positional parameters
$@
"­$1" "­$2" "­$3" ...
$*
A string of positional params > 0
$#
Number of positional params - 1
$?
Exit status of last command run

Run a script

source myscript
Run in current shell
./myscript
Run script in a subshell
myscript
Run script in subshell. Must be in $PATH

Functions

Two ways to define:
function myfunction { ... }
myfunction ( ) { ... }

Call a function:
myfunction arg1 arg2

Keywords:
local - Limit variable scope. $@, $*, $#, $0, $1 are automa­tically local.

String operators

${varname:-word}
Returns word
${varname:=word}
Sets and returns word
${varname:?message}
Prints message and exits
${varname:offset:length}
Returns substring (1-ind­exed)
${varname:+word}
If varname is defined, then returns word. Else returns null.
If varname does not exist or is null, then string operators follow the behavior above (except for the :+).

Patter­n-m­atching operators

${varname#pattern}
Match shortest from the start and delete
${varname##pattern}
Match longest from the start and delete
${varname%pattern}
Match shortest from the end and delete
${varname%%pattern}
Match longest from the end and delete
${varname/pattern/replace}
Match longest and replace
${varname//pattern/replace}
Match all and replace

If / else conditions

statement1 && statement2
If statement1 runs, then run statement2
statement1 || statement2
If statement1 fails, then run statement2
statement1 -a statement2
statement1 AND statement2
statement1 -o statement2
statement1 OR statement2
-lt, -le, -eq, -gt, -ge, -ne
Integer compar­isons
=, !=, <, >
String compar­isons
-n str1
str1 has length > 0
-z str1
str1 has length 0
-d file
file exists and is a directory
-e file
file exists
-f file
file exists and is a regular file
-r file
User has read permission on file
-s file
file exists and is not empty
-w file
User has write permission on file
-x file
User has execute permission on file, or search permission if it's a directory
-N file
file was modified since it was last read
-O file
User owns file
-G file
file's group ID matches one of the user's group IDs
file1 -nt file2
file1 has a newer modifi­cation time than file2
All of the above conditions must go in square brackets ([ ]) because if/else test against exit codes. Parent­heses indicting order of operations within square brackets must be escaped with a backslash.

Other flow control

for - Defaults to looping through $@. Set loop delimiter using $IFS.

case expression in
 ­ ­ ­ pattern1 )
 ­ ­ ­ ­ ­ ­ ­ statements ;;
 ­ ­ ­ pattern2 | pattern3 )
 ­ ­ ­ ­ ­ ­ ­ statements ;;
 ­ ­ ­ ...
 ­ ­ ­ * )
 ­ ­ ­ ­ ­ ­ ­ last statements ;;
esac

while condition ; do statements ; done
until condition ; do statements ; done

There is also a select condition that operates like case on user input.

Subshell inheri­tance

These are inherited by subshells:
- the current directory
- enviro­nment variables
- standard input, output, error, and other open file descri­ptors
- signals that are ignored