Bash Cheatsheet

This site is a reference for the scripting language Bash

Last updated on 14 June, 2021 at 09:50:16 Optimized for

Bash (Bourne Again Shell) is a shell language build on-top of the orignal Bourne Shell which was distributed with V7 Unix in 1979 and became the standard for writing shell scripts. Today it is primary to most Linux distributions, MacOS and it has even recently been enabled to run on Windows through something called WSL (Windows Subsystem for Linux).

Website logo
For the full experience we recommend viewing this website on a desktop or tablet.

File Test Operators

Used for testing of files files in shellscripts

Testing files in scripts is easy and straight forward. This is where shell scripting starts to show its glory! In Bash you can do file testing for permissions, size, date, filetype or existence.

Flag Description
-e

File exists

-a

File exists (identical to -e but is deprecated and outdated)

-f

File is a regular file (not a directory or device file)

-s

File is not zero size

-d

File is a directory

-b

File is a block device

-c

File is a character device

-p

File is a pipe

-h

File is a symbolic link

-L

File is a symbolic link

-S

File is a socket

-t

File (descriptor) is associated with a terminal device

-r

File has read permission (for the user running the test)

-w

File has write permission (for the user running the test)

-x

File has execute permission (for the user running the test)

-g

Set-group-id (sgid) flag set on file or directory

-u

Set-user-id (suid) flag set on file

-k

Sticky bit set

-O

You are owner of file

-G

Group-id of file same as yours

-N

File modified since it was last read

f1 -nt f2

File f1 is newer than f2

f1 -ot f2

File f1 is older than f2

f1 -ef f2

Files f1 and f2 are hard links to the same file

!

Not operator, will reverse the any test and return true if a condition is absent

String Comparison

Used for string comparison in Bash

This section describes how to compare strings in Bash.

Flag Description
=

Is equal to

==

Same as above, except the use of double equal symbols

!=

Is not equal to

<

Is less than ASCII alphabetical order

>

Is greater than ASCII alphabetical order

-z

String is null (i.e. zero length)

-n

String is not null (i.e. !zero length)

Integer Comparison

Used for comparing numbers

How to compare integers or arithmetic expressions in shell scripts.

Flag Description
-eq

Is equal to

-ne

Is not equal to

-gt

Is greater than

-ge

Is greater than or equal to

-lt

Is less than

-le

Is less than or equal to

<

Is less than – place within double parentheses

<=

Is less than or equal to (same rule as previous row)

>

Is greater than (same rule as previous row)

>=

Is greater than or equal to (same rule as previous row)

Compound Operators

The compound operators work with the test command or may occur within single brackets [ <expr> ]
Useful for boolean expressions and is similar to && and ||
Flag Description
-a

Logical and

-o

Logical or

List Constructs

Provides a means of processing commands consecutively and in effect is able to replace complex if/then/case structures.

Construct Description
&&

And construct

||

Or construct

Job Identifiers

Job control allows you to selectively stop (suspend) the execution of processes and continue their execution at a later point in time.

Notation Description
%N

Job number [N]

%S

Invocation (command-line) of job begins with string S

%?S

Invocation (command-line) of job contains within it string S

%%

"current" job (last job stopped in foreground or started in background)

%+

"current" job (last job stopped in foreground or started in background)

%-

Last job

%!

Last background process

Signals

System V Signals

UNIX System V Signals.

Name Number Action Description
SIGHUP

1

Exit

Hangs up

SIGINT

2

Exit

Interrupts

SIGQUIT

3

core dump

Quits

SIGILL

4

core dump

Illegal instruction

SIGTRAP

5

core dump

Trace trap

SIGIOT

6

core dump

IOT instruction

SIGEMT

7

core dump

MT instruction

SIGFPE

8

core dump

Floating point exception

SIGKILL

9

exit

Kills (cannot be caught or ignored)

SIGBUS

10

core dump

Bus error

SIGSEGV

11

core dump

Segmentation violation

SIGSYS

12

core dump

Bad argument to system call

SIGPIPE

13

exit

Writes on a pipe with no one to read it

SIGALRM

14

exit

Alarm clock

SIGTERM

15

exit

Software termination signal

Reserved Exit Codes

Useful for debugging a script. Exit takes integer args in the range 0-255.

Exit Code No. Description
1

Catchall for general errors

2

Misuse of shell builtins

126

Command invoked cannot execute

127

Command not found

128

Invalid argument to exit

128+n

Fatal error signal "n"

130

Script terminated by Control-C

Sending Control Signals

You can use these key-combinations to send signals or control the output. Check your stty settings. Suspend and resume of output is usually disabled if you are using "modern" terminal emulations. The standard xterm supports Ctrl+S and Ctrl+Q by default.

Check your stty settings. Suspend and resume of output is usually disabled if you are using "modern" terminal emulations. The standard xterm supports Ctrl+S and Ctrl+Q by default.
Key Combo Description
Ctrl+C

The interrupt signal, sends SIGINT to the job running in the foreground

Ctrl+Y

The delayed suspend character. Causes a running process to be stopped when it attempts to read input from the terminal. Control is returned to the shell, the user can foreground, background or kill the process. Delayed suspend is only available on operating systems supporting this feature.

Ctrl+Z

The suspend signal, sends a SIGTSTP to a running program, thus stopping it and returning control to the shell.

Ctrl + s

Stops the output to the screen (for long running verbose command)

Ctrl + q

Allow output to the screen (if previously stopped using command above)

Ctrl + l

Clear the screen

Command Editing

Keyboard Shortcuts

Shortcuts to use in the CLI for swiftly editing a command. These shortcuts are provided by the GNU Readline library.

Key Combo Description
Ctrl + a

Go to the start of the command line

Ctrl + e

Go to the end of the command line

Ctrl + k

Delete from cursor to the end of the command line

Ctrl + u

Delete from cursor to the start of the command line

Ctrl + w

Delete from cursor to start of word (i.e. delete backwards one word)

Ctrl + y

Paste word or text that was cut using one of the deletion shortcuts (such as the one above) after the cursor

Ctrl + xx

Move between start of command line and current cursor position (and back again)

Alt + b

Move backward one word (or go to start of word the cursor is currently on)

Alt + f

Move forward one word (or go to end of word the cursor is currently on)

Alt + d

Delete to end of word starting at cursor (whole word if cursor is at the beginning of word)

Alt + c

Capitalize to end of word starting at cursor (whole word if cursor is at the beginning of word)

Alt + u

Make uppercase from cursor to end of word

Alt + l

Make lowercase from cursor to end of word

Alt + t

Swap current word with previous

Ctrl + f

Move forward one character

Ctrl + b

Move backward one character

Ctrl + d

Delete character under the cursor

Ctrl + h

Delete character before the cursor

Ctrl + t

Swap character under cursor with the previous one

File Types

This is very different from Windows but straight forward once you get it.

Symbol Meaning
-

Regular file

d

Directory

l

(Symbolic) Link

c

Character device

s

Socket

p

Named pipe

b

Block device

Special Files

Files that are read by the shell. Listed in order of their execution.

File Info
/etc/profile

Executed automatically at login

~.bash_profile
~/.bash_login
~.profile

Whichever is found first is executed at login

~/.bashrc

Is read by every nonlogin shell

Permissions

Now you may know what that arcane looking string rwxrwxrwx is when you invoke ls -l

Code Description
s

Setuid when in user column

s

Setgid when in group column

t

Sticky bit

0
-

The access right that is supposed to be on this place is not granted.

4
r

Read access is granted to the user category defined in this place

2
w

Write permission is granted to the user category defined in this place

1
x

Execute permission is granted to the user category defined in this place

u

User permissions

g

Group permissions

o

Others permissions

String Manipulation

Bash supports a surprisingly big number of string operations! Unfortunately, these tools lack a unified focus. Some are a subset of parameter substitution, and others fall under the functionality of the UNIX expr command. This results in inconsistent command syntax and overlap of functionality.

MacOS built-in bash is from 2007 and won't support many of these.
Pattern Description
${#var}

Find the length of the string

${var%pattern}

Remove from shortest rear (end) pattern

${var%%pattern}

Remove from longest rear (end) pattern

${var:position}

Extract substring from $var at $position

${var:num1:num2}

Substring

${var#pattern}

Remove from shortest front pattern

${var##pattern}

Remove from longest front pattern

${var/pattern/string}

Find and replace (only replace first occurrence)

${var//pattern/string}

Find and replace all occurrences

${!prefix*}

Expands to the names of variables whose names begin with prefix.

${var,}
${var,pattern}

Convert first character to lowercase

${var,}
${var,pattern}

Convert all characters to lowercase

${var^}
${var^pattern}

Convert first character to uppercase

${var^^}
${var^^pattern}

Convert all character to uppercase

${string/substring/replacement}

Replace first match of $substring with $replacement

${string//substring/replacement}

Replace all matches of $substring with $replacement

${string/#substring/replacement}

If $substring matches front end of $string, substitute $replacement for $substring

${string/%substring/replacement}

If $substring matches back end of $string, substitute $replacement for $substring

expr match "$string" '$substring'

Length of matching $substring* at beginning of $string

expr "$string" : '$substring'

Length of matching $substring* at beginning of $string

expr index "$string" $substring

Numerical position in $string of first character in $substring* that matches [0 if no match, first character counts as position 1]

expr substr $string $position $length

Extract $length characters from $string starting at $position [0 if no match, first character counts as position 1]

expr match "$string" '\($substring\)'

Extract $substring*, searching from beginning of $string

expr "$string" : '\($substring\)'

Extract $substring* , searching from beginning of $string

expr match "$string" '.*\($substring\)'

Extract $substring*, searching from end of $string

expr "$string" : '.*\($substring\)'

Extract $substring*, searching from end of $string

Quoting

The following text shows characters that need to be quoted if you want to use their literal symbols and not their special meaning.

Everything between double-quotes is taken literally, except $<alnum> ($a, $1) ` and ", \ and line-breaks.
Everything between single-quotes is taken literally, except '.
Using a dollar sign before double-quotation or single-quotation causes some special behavior. $"..." is the same as "..." except that locale translation is done and:wq $'...' is similar to $'...' except that the quoted string is processed for escape sequences.
Symbol Literal Meaning
;

Command seperator

&

Background execution

()

Command grouping

|

Pipe

< > &

Redirection symbols

* ? [ ] ~ + - @ !

Filename metacharacters

" ' \

Used in quoting characters

$

Variable, command or arithmetic substituion

#

Start a command that ends on a linebreak

space tab newline

Word seperators

Command Parameters

Command parameters, also known as arguments, are used when invoking a Bash script.

Description Command
$0

Name of the script itself

$1 … $9

Parameter 1 ... 9

${10} ... ${nn}

Positional parameter 10 or greater

$*

Expands to the positional parameters, starting from one

$-

Current options

$_

Contains the absolute file name of the shell or script being executed

$$

Process id of the shell

$?

Exit status of the most recently executed command

$@

All arguments as separate words

$#

Number of arguments

$!

PID of most recently backgrounded process

History Expansion

Enables use and manipulation of previous commands.

Description Command
!

Starts a history substitution

!!

Refers to the last command

!n

Refers to the -th command line

!-n

Refers to the current command line minus

!string

Refers to the most recent command starting with

!string:p

Print out the command that !string would run (also adds it as the latest command in the command history)

!$

The last word of the previous command (same as Alt + .)

!$:p

Print out the word that !$ would substitute

!*

The previous command except for the last word (e.g. if you type ‘_find somefile.txt /’, then !* would give you ‘_find somefile.txt’)

!*:p

Print out what !* would substitute

!?string?

Refers to the most recent command containing (the ending ? is optional)

^string1^string2^

Quick substitution. Repeats the last command, replacing with

!#

Refers to the entire command line typed so far

Variable Operations

Parameter Expansions

Set but null Expression Set and not null Unset
${parameter:-word}

Substitute parameter

Substitute word

Substitute word

${parameter-word}

Substitute parameter

Substitute null

Substitute word

${parameter:=word}

Substitute parameter

Assign word

Assign word

${parameter=word}

Substitute parameter

Substitute null

Assign word

${parameter:?word}

Substitute parameter

Error, exit

Error, exit

${parameter?word}

Substitute parameter

Substitute null

Error, exit

${parameter:+word}

Substitute word

Substitute null

Substitute null

${parameter+word}

Substitute word

Substitute word

Substitute null

Bash Globbing

Bash cannot recognize RegEx but understand globbing. Globbing is done to filenames by the shell while RegEx is used for searching text.

Glob Description
*

Matches zero or more occurences of a given pattern

?

Matches zero or one occurences of a given pattern

+

Matches one or more occurences of a given pattern

!

Negates any pattern matches — reverses the pattern so to speak

Character Classes in BRE

A character class is a pattern you can use instead of a regular expression. They are easier to remember and work with.

Character classes has the format [:CharClass:]
Character Class Equivalent Explanation
[:lower:]

[a-z]

Lowercase letters.

[:upper:]

[A-Z]

Uppercase letters.

[:alpha:]

[A-Za-z]

Alphabetic letters, both upper- and lowercase.

[:digit:]

[0-9]

Numbers 0-9.

[:alnum:]

[a-zA-Z0-9]

Alphanumeric: both letters (upper- + lowercase) and digits.

[:xdigit:]

[0-9A-Fa-f]

Hexadecimal digits.

[:space:]

[ \t\n\r\f\v]

Whitespace. Spaces, tabs, newline and similar.

[:punct:]

Symbols (minus digits and letters).

[:print:]

[[:graph] ]

Printable characters (spaces included).

[:blank:]

[ \t]

Space and tab characters only.

[:graph:]

[^ [:cntrl:]]

Graphically printable characters excluding space.

[:cntrl:]

Control characters. Non-printable characters.

Flow Control

Flow control structures in Bash are straight forward, albeit Bash is unforgiving if you get the syntax wrong.

Keyword Description
if

Test a condition.

else

Test a condition and use a fallback if the test fails.

elif

Provides additional testing plus a fallback if all tests fail. You may skip the elif conditions or add as many in-between as you like. Similarly, you may skip the else fallback

for

Iterate over a sequence, a list or anything as far as the imagination goes

while

While a condition is true - repeat until that condition is no longer true

until

The inverse of the while loop - as long as the test-command fails, the until-loop continues

select

Used for easy menu generation. Any statement within can be another select construct, thus enabling sub-menu creation

case

Alternative if-branching. Each case is an expression which matches a given pattern (i.e., a case)

Overview of Bash Symbols

Here we have gathered a collection of all arcane syntax along with a brief description. A bunch of these symbols are repeated from earlier but many are new - this is a good starting point if you are new to the language.

Description Builtin
#

Used for comments

$

Used for parameters and variables. Has a bunch of edge cases

( )

Is used for running commands in a subshell

$( )

Is used for saving output of commands that are send to run in a subshell

(( ))

Is used for arithmetic

$(( ))

Is used for retrieving the output of arithmetic expressions, either for usage with a command or to save the output in a variable.

$[]

Deprecated integer expansion construct which is replaced by $(( )). Evaluates integers between the square brackets

[ ]

Is used for testing and is a built-in. Is useful in some cases for filename expansion and string manipulation.

[[ ]]

Is used for testing. This is the one you should use unless you can think of a reason not to.

<( )

Used for process substitution and is similar to a pipe. Can be used whenever a command expects a file and you can use multiple at once.

{ }

Is used for expansion of sequences

${ }

Is used for variable interpolation and string manipulation

|

Is a pipe which is used for chaining commands together

<

Used for feeding input to commands from a file

>

Used for sending output to a file and erasing any previous content in that file.

||

Logical or

&&

Logical and

-

Used for option prefixes

--

Used for the long-option prefixes

&

Used to send a job to the background

<<WORD
<<-WORD
<<'WORD'
<<-'WORD'

Is used for heredocs

<<<

Is used for herestrings

>>

Is used to append output to a file

' '

Single quotes are used to preserve the literal value

" "

Double quotes are used to preserve the literal value of all characters except $, ` ` and \

\

Backslash is used to escape otherwise interpreted symbols/characters which has a special meaning

/

Used for seperating the components of a filename

:

Similar to a NOP – a do nothing operation. It is a shell builtin with an exit status of true

;

Used to seperate commands intended to run sequentally

,

Used for linking together arithmetic operations. All are evalutated but only the last is returned

.

Represents the current directory

..

Represents parent directory

~

Expands to home directory

` `

Is deprecated and should not be used. Read further in its respective section

Bash Builtins

Shell builins are built into Bash are often very (if not extremely) fast compared to external programs. Some of the builtins are inherited from the Bourne Shell (sh) — these inherited commands will also work in the original Bourne Shell.

Symbol Usage
:

Equivalent to true

.

Reads and executes commands from a designated file in the current shell

[

Is a synonym for test but requires a final argument of ]

alias

Defines an alias for the specified command

bg

Resumes a job in background mode

bind

Binds a keyboard sequence to a read line function or macro

break

Exits from a for, while, select, or until loop

builtin

Executes the specified shell built-in command

caller

Returns the context of any active subroutine call

case

Used to simplify complex conditionals

cd

Changes the current directory to the specified directory

command

Executes the specified command without the normal shell lookup

compgen

Generates possible completion matches for the specified word

complete

Displays how the specified words would be completed

comopt

Print or change the completion options for a command

continue

Resumes the next iteration of a for, while, select, or until loop

declare

Declares a variable or variable type

dirs

Displays a list of currently remembered directories

disown

Removes the specified jobs from the jobs table for the process

echo

Displays the specified string to STDOUT

enable

Enables or disables the specified built-in shell command

eval

Concatenates the specified arguments into a single command, and executes the command.

exec

Replaces the shell process with the specified command

exit

Forces the shell to exit with the specified exit status

export

Sets the specified variables to be available for child shell processes

fc

Selects a list of commands from the history list

fg

Resumes a job in foreground mode

getopts

Parses the specified positional parameters

hash

Finds and remembers the full pathname of the specified command

help

Displays a help file

history

Displays the command history

if

Used for branching

jobs

Lists active jobs

kill

Sends a system signal to the specified process ID (PID)

let

Evaluates each argument in a mathematical expression

local

Creates a limited-scope variable in a function

logout

Exits a login shell

mapfile

Reads lines from standard input into an indexed array

popd

Removes entries from the directory stack

printf

Displays text using formatted strings

pushd

Adds a directory to the directory stack

pwd

Displays the pathname of the current working directory

read

Reads one line of data from STDIN, and assigns it to a variable

readonly

Reads one line of data from STDIN, and assigns it to a variable that can’t be changed.

return

Forces a function to exit with a value that can be retrieved by the calling script

set

Sets and displays environment variable values and shell attributes

shift

Rotates positional parameters down one position

shopt

Toggles the values of variables controlling optional shell behavior

source

Reads and executes commands from a designated file in the current shell

suspend

Suspends the execution of the shell until a SIGCONT signal is received

test

Returns an exit status of 0 or 1 based on the specified condition

times

Displays the accumulated user and system shell time

trap

Executes the specified command if the specified system signal is received

type

Displays how the specified words would be interpreted if used as a command

typeset

Declares a variable or variable type

ulimit

Sets a limit on the specific resource for system users

umask

Sets default permissions for newly created files and directories

unalias

Removes specified alias

unset

Removes the specified environment variable or shell attribute

until

Loop that is very similar to the while-loop except that it executes until the test-command executes succesfully. As long as the test-command fails, the until-loop continues.

wait

Make the shell wait for a job to finish

while

Waits for the specified process to complete, and returns the exit status

Online Resources & Books