Ryan Jacobs


BASH Cheatsheet

If you run into any problems, check out the Troubleshooting section.

The One Command That Everyone Should Know

# The One Command That Everyone Should Know... is 'man'.
# Every command has it's own manual page.
# Want to know a command's purpose and/or usage? Read it's man page!

# Usage: man [topic]
ryan@delta ~ $ man ls

# Usage: man -k <search_term>
ryan@delta ~ $ man -k zip
bzip2 (1)            - a block-sorting file compressor, v1.0.6
gzip (1)             - compress or expand files
zip (1)              - package and compress (archive) files

Command Synopsis

A command synopsis tells you how to use a command. It looks like this:

# command <mandatory> [optional]

The synopsis for the echo command (straight from the man page):

# echo [SHORT-OPTION]... [STRING]...

The '...' means that you can repeat that part. Now we can see that the echo command takes multiple & optional short options and also multiple & optional strings.

Common Commands

## Navigation ##
ls [dir]                 # List directory contents
ls -a                    # List all contents, i.e. hidden files
ls -l                    # Long listing
ls -1                    # List every item on a new line
ls -lh                   # Long listing, human readable
ls -lh *.jpg             # List all .jpg files

cd [dir]                 # Change into directory
cd ..                    # Go up a directory
cd ../..                 # Go up two directories
cd /                     # Go to root directory

pwd                      # Print working directory
du -sh                   # Show directory's disk usage
## File Manipulation ##
touch <file>             # Create file
mkdir <dirname>          # Make a directory

cat   <file>             # Output file contents
wc -l <file>             # Count lines in file
wc -w <file>             # Count words in file
wc -c <file>             # Count characters in file
grep <pattern> <file>    # Search file for pattern

head [-n lines] <file>   # Get n lines from the top of the file
tail [-n lines] <file>   # Get n lines from the bottom of the file

rm     <file>            # Remove file
rm -r  <folder>          # Remove recursively
rm -rv <folder>          # Remove recursively and verbosely
rm -f  <file>            # Remove forcefully

cp <src> <dest>          # Copy a file
mv <src> <dest>          # Move a file

ln    <file> <link>      # Create a hardlink
ln -s <file> <link>      # Create a symlink
## Information & Administration ##
date                     # Show date and time
w                        # Show who is logged in and what they are doing
top                      # Dynamic process list

kill    <pid>            # Kill a process based on PID (Process ID)
kill -9 <pid>            # Force kill PID
killall <process_name>   # Kill a process based on name
## Other ##
echo  <string>           # Output a string
sleep <seconds>          # Pause for n seconds

Terminal Shortcuts

## Terminal Shortcuts ##
Ctrl+C                   # Kill current process
Ctrl+L                   # Clear terminal
Ctrl+A                   # Move cursor to beginning of prompt
Ctrl+E                   # Move cursor to end of prompt
Ctrl+Shift+C             # Copy terminal selection to clipboard
Ctrl+Shift+V             # Paste clipboard into terminal
Shift + Page Up/Down     # Scroll up/down the terminal

BASH Expansion

## Braces! ##
echo {1,2,3}                   # Expands to "1 2 3"
echo {1..5}                    # Expands to "1 2 3 4 5"
echo {01..05}                  # Expands to "01 02 03 04 05"
echo {a..e}                    # Expands to "a b c d e"
echo {word1,word2,word3}       # Expands to "word1 word2 word3"

mkdir {A..Z}                   # Creates 26 directories named A thru Z
touch File_{A..C}              # Creates files: File_A, File_B, and File_C
touch main.{c,h}               # Creates files: main.c and main.h

BASH Wildcards

* represents anything. Hello*.txt would satisfy 'HelloWorld.txt', 'Hellooo.txt', etc.
? represents a single character. R?an would satisfy 'Ryan', 'Raan', 'Rban', etc.

## Wildcards! ##
ls *.jpg                       # List all files with the .jpg extension
rm *.jpg                       # Remove all .jpg files
rm ??.txt                      # Remove all two character .txt files
rm *                           # REMOVE EVERYTHING!!!

Semi-colon, &&, and ||

## Semi-colon Operator ##
#  means 'do that after this'
ryan@delta ~ $ echo hello; echo world
hello
world
## && Operator ##
#  means 'only if successful, do that after this'
ryan@delta ~ $ echo hello && echo world
hello
world

ryan@delta ~ $ Fake_Command && echo world
bash: Fake_Command: command not found
## || Operator ##
#  means 'only if failure, do that after this'
ryan@delta ~ $ Fake_Command || echo "Failure!"
bash: Fake_Command: command not found
Failure!
## Mixing semi-colon, &&, and || ##
ryan@delta ~ $ touch MyFile
ryan@delta ~ $ echo "Removing..."; rm MyFile && echo "Yay!" || echo "Boo!"; echo "Done."
Removing...
Yay!
Done.

ryan@delta ~ $ echo "Removing..."; rm MyFile && echo "Yay!" || echo "Boo!"; echo "Done."
Removing...
rm: cannot remove ‘MyFile’: No such file or directory
Boo!
Done.

BASH Job Control

## BASH Job Control ##
<command> &              # Run command in the background
<command> &>/dev/null    # Suppress command's output
<command> &>/dev/null &  # Suppress command's output and run in background

Ctrl-Z                   # Stop current process
fg                       # Put stopped process in foreground
bg                       # Put stopped process in background
jobs                     # List current running jobs

Permissions

## File Permissions ##
chmod +x <file>          # Make file executable
chmod -x <file>          # Make file not executable

Basic Stream Redirection

#############################
##         Piping          ##
#############################
# Takes the output of one command and uses it as the input to another.
#
# Here we'll get the number of files in directory by counting lines
# of 'ls' by using the command 'wc -l'.
ryan@delta ~ $ ls
01  02  03  04  05  06  07  08  09  10
ryan@delta ~ $ ls -1 | wc -l
10
#############################
##  Redirection to a File  ##
#############################
#  Use the '>' operator to save the output of a command to a file.
ryan@delta ~ $ ls
ryan@delta ~ $ echo "Hello world!" > file
ryan@delta ~ $ ls
file
ryan@delta ~ $ cat file
Hello world!

# Use the '>>' operator to append to the file instead of overwriting.
ryan@delta ~/example $ echo "I am on line two!" >> file
ryan@delta ~/example $ cat file
Hello world!
I am on line two!

Troubleshooting

I can't do anything with spaces!

This is because of how BASH handles strings. BASH strings must be single-quoted, double-quoted, or space-escaped.
An Example:

# Let's create a file called: Hello World.txt
ryan@delta ~ $ touch Hello World.txt

# Uh oh, BASH interpreted our filename as two separate strings
ryan@delta ~ $ ls
-rw-r--r-- 1 ryan users 0 Sep 26 19:03 Hello
-rw-r--r-- 1 ryan users 0 Sep 26 19:03 World.txt

# Let's try it with single quotes
ryan@delta ~ $ touch 'Hello World.txt'
ryan@delta ~ $ ls -l
-rw-r--r-- 1 ryan users 0 Sep 26 19:03 Hello World.txt

# Let's try it with double quotes
ryan@delta ~ $ touch "Hello World.txt"
ryan@delta ~ $ ls -l
-rw-r--r-- 1 ryan users 0 Sep 26 19:03 Hello World.txt

# Let's try it with space-escaping (a backslash before every space)
ryan@delta ~ $ touch Hello\ World.txt
ryan@delta ~ $ ls -l
-rw-r--r-- 1 ryan users 0 Sep 26 19:03 Hello World.txt

# Oh boy! They all work!

I can't use exclamation marks!

Certain symbols have specific meanings in BASH. Such as the semi-colon, &&, ||, or exclamation mark. Single-quotes tell BASH to interpret the string literally.

# Exclamation mark in double quotes. Boo, it fails.
ryan@delta ~ $ echo "I! AM! A!WEIRD!STRING!"
bash: !WEIRD!STRING!: event not found

# Exclamation mark in single quotes. Yay, it works!
ryan@delta ~ $ echo 'I! AM! A!WEIRD!STRING'
I! AM! A!WEIRD!STRING