Bash CheatSheet

If you're looking to improve your command-line skills, this bash cheat sheet is an essential resource. Created by experienced developers and designed to be both comprehensive and easy to use, this cheat sheet covers everything from basic commands to advanced scripting techniques. Whether you're a beginner or an experienced user, this cheat sheet will help you streamline your workflow, increase your productivity, and take your bash skills to the next level.

With clear and concise explanations of each command, as well as helpful examples and tips for best practices, this cheat sheet is perfect for anyone who wants to become an expert in bash. Plus, it's available in a printable format, so you can keep it handy at your desk or on-the-go. So why wait? Download this must-have resource today and start mastering the power of bash!


Table of Content




# Getting started Bash


What is Bash ?

Bash is the shell program, or command language interpreter, for the GNU operating system.

A shell program is typically an executable binary that takes commands that you type and (once you hit return), translates those commands into (ultimately) system calls to the Operating System API.

Bash can also read and execute commands from a file, called a shell script. Like most Unix shells, it supports filename globbing (wildcard matching), piping, here documents, command substitution, variables, and control structures for condition-testing and iteration. The keywords, syntax, dynamically scoped variables and other basic features of the language are all copied from sh. Other features, e.g., history, are copied from csh and ksh. Bash is a POSIX-compliant shell, but with a number of extensions.

The name is an acronym for the Bourne-Again SHell, a pun on Stephen Bourne, the author of the direct ancestor of the current Unix shell sh, which appeared in the Seventh Edition Bell Labs Research version of Unix.

helloWorld.sh

#!/bin/bash

VAR="bestforstudy.com"
echo "Hello World, $VAR!" 
# Output: Hello World, bestforstudy.com!

Variables

SITENAME="bestforstudy.com"

echo ${SITENAME}    # => bestforstudy.com
echo $SITENAME      # => bestforstudy.com
echo "$SITENAME"    # => bestforstudy.com
echo '$SITENAME'    # => $SITENAME
echo "${SITENAME}!" # => bestforstudy.com!

SITENAME = "bestforstudy.com" # => Error (about space)

Comments

# This is an inline Bash comment.


: '
    Multi-line comments
'

Arguments

Expression Description
$1 $9 Parameter 1 ... 9
$0 Name of the script itself
$1 First argument
${10} Positional parameter 10
$# Number of arguments
$$ Process id of the shell
$* All arguments
$@ All arguments, starting from first
$- Current options
$_ Last argument of the previous command

Functions

get_website_name() {
    echo "bestforstudy.com"
}


echo "You access $(get_name)"
# Output: You access bestforstudy.com

Conditionals

# Syntax if
if [ condition ] ; then
Command(s)
fi


# Syntax if-else statement
if [ condition ]; then
Command(s)
else
Command(s)
fi


# Synxtax if-elif-else statement
if [ condition ]; then
Command(s)
elif [ condition ]; then
Command(s)
..
else
Command(s)
fi


# Example 1
echo "Enter a number"
read n
if [ $n -lt 100 ]; then
printf "$n is less than 100\n"
fi


# Example 2
echo "Enter username"
read un
echo "Enter password"
read pw
if [[ "$un" == "admin" && "$pw" = "superuser" ]]; then
echo "Login Successful."
fi


# Example 3
if [[ -z "$string" ]]; then
    echo "String is empty"
elif [[ -n "$string" ]]; then
    echo "String is not empty"
fi

Brace expansion

echo {A,B}.js
Expression Description
{A,B} Same as A B
{A,B}.js Same as A.js B.js
{1..5} Same as 1 2 3 4 5

Shell execution

# Syntax
$( <COMMANDS> )
# Similar to
` <COMMANDS> `


# Example
echo "Your username is $(USERNAME)"
# is similar to
echo "Your username is `USERNAME`"

# Parameter expansions in Bash


Syntax

Code Description
${FOO%suffix} Remove suffix
${FOO#prefix} Remove prefix
${FOO%%suffix} Remove long suffix
${FOO##prefix} Remove long prefix
${FOO/from/to} Replace first match
${FOO//from/to} Replace all
${FOO/%from/to} Replace suffix
${FOO/#from/to} Replace prefix

Substrings Syntax

Expression Description
${FOO:0:3} Substring (position, length)
${FOO:(-3):3} Substring from the right

Length Syntax

Expression Description
${#FOO} Length of $FOO

Default values Syntax

Expression Description
${FOO:-val} $FOO, or val if unset
${FOO:=val} Set $FOO to val if unset
${FOO:+val} val if $FOO is set
${FOO:?message} Show message and exit if $FOO is unset

Substitution

echo ${site:-bestforstudy}  
# Output: $site or "bestforstudy"


STR="/path/to/bestforstudy.cpp"
echo ${STR%.cpp}    # /path/to/bestforstudy
echo ${STR%.cpp}.o  # /path/to/bestforstudy.o
echo ${STR%/*}      # /path/to

echo ${STR##*.}     # cpp (extension)
echo ${STR##*/}     # bestforstudy.cpp (basepath)

echo ${STR#*/}      # path/to/bestforstudy.cpp
echo ${STR##*/}     # bestforstudy.cpp

echo ${STR/bestforstudy/google} # /path/to/google.cpp

Slicing

name="Jack"

echo ${name}           
# Output: Jack

echo ${name:0:2}       
# Output: Ja

echo ${name::2}        
# Output: Ja

echo ${name::-1}       
# Output: Jac

echo ${name:(-1)}      
# Output: k

echo ${name:(-2)}      
# Output: ck

echo ${name:(-2):2}    
# Output: ck

length=2
echo ${name:0:length}  
# Output: Ja

basepath & dirpath

SRC="/path/to/site/bestforstudy.com"

BASEPATH=${SRC##*/}   
echo $BASEPATH  
# Output: "bestforstudy.com"

DIRPATH=${SRC%$BASEPATH}
echo $DIRPATH   
# Output: "/path/to/site/"

Transform

STR="HELLO WORLD!"
echo ${STR,}   
# Output: hELLO WORLD!
echo ${STR,,}  
# Output: hello world!

STR="hello world!"
echo ${STR^}   
# Output: Hello world!
echo ${STR^^}  
# Output: HELLO WORLD!

ARR=(hello World)
echo "${ARR[@],}" 
# Output: hello world
echo "${ARR[@]^}" 
# Output: Hello World

# Arrays in Bash


Defining arrays

# declare construct
declare -a Numbers=(1 2 3 4 5 6 7 8 9 10)

Sports=('Football' 'Baseball' 'Basketball')

Sports[0]="Football"
Sports[1]="Baseball"
Sports[2]="Basketball"

ARRAY2=(arr{1..2}) 
# Output: arr1 arr2

ARRAY3=({A..D})    
# Output: A B C D

Array Indexing

- -
${Sports[0]} First element
${Sports[-1]} Last element
${Sports[*]} All elements
${Sports[@]} All elements
${#Sports[@]} Number of all
${#Sports} Length of 1st
${#Sports[3]} Length of nth
${Sports[@]:3:2} Range
${!Sports[@]} Keys of all

Iteration

Sports=('Football' 'Baseball' 'Basketball')

for e in "${Sports[@]}"; do
    echo $e
done

# loop with index
for i in "${!Sports[@]}"; do
  printf "%s\t%s\n" "$i" "${Sports[$i]}"
done

Operations

# Push value to array
Sports=("${Sports[@]}" "Swimming")     

# Another way to Push value to array
Sports+=('Swimming')                   

# Remove value in by regex if match
Sports=( ${Sports[@]/Ap*/} )             

# Remove one item
unset Sports[2]                          

# Duplicate
Sports=("${Sports[@]}")                  

# Concatenate
Sports=("${Sports[@]}" "${Veggies[@]}")  

# Read from file
lines=(`cat "logfileName"`)                  

Arrays as arguments

function extract() {
    local -n myarray=$1
    local idx=$2
    echo "${myarray[$idx]}"
}

Sports=('Football' 'Baseball' 'Basketball')

extract Sports 1
# Result: Baseball

# Dictionaries in Bash


How to Define

declare -A sounds

sounds[dog]="bark"
sounds[cow]="moo"
sounds[bird]="tweet"
sounds[wolf]="howl"

Working with dictionaries

# Dog's sound
echo ${sounds[dog]}

# All values
echo ${sounds[@]}

# All keys
echo ${!sounds[@]}

# Number of elements
echo ${#sounds[@]}

# Delete dog
unset sounds[dog]

Iteration

for val in "${sounds[@]}"; do
    echo $val
done
# Output: Show all sounds values


for key in "${!sounds[@]}"; do
    echo $key
done
# Output: Show all sounds key

# Conditionals in Bash


Integer conditions

Condition Description
[[ NUM -eq NUM ]] Equal
[[ NUM -ne NUM ]] Not equal
[[ NUM -lt NUM ]] Less than
[[ NUM -le NUM ]] Less than or equal
[[ NUM -gt NUM ]] Greater than
[[ NUM -ge NUM ]] Greater than or equal
(( NUM < NUM )) Less than
(( NUM <= NUM )) Less than or equal
(( NUM > NUM )) Greater than
(( NUM >= NUM )) Greater than or equal

String conditions

Condition Description
[[ -z STR ]] Empty string
[[ -n STR ]] Not empty string
[[ STR == STR ]] Equal
[[ STR = STR ]] Equal (Same above)
[[ STR < STR ]] Less than (ASCII)
[[ STR > STR ]] Greater than (ASCII)
[[ STR != STR ]] Not Equal
[[ STR =~ STR ]] Regexp

File conditions

Condition Description
[[ -e FILE ]] Exists
[[ -d FILE ]] Directory
[[ -f FILE ]] File
[[ -h FILE ]] Symlink
[[ -s FILE ]] Size is > 0 bytes
[[ -r FILE ]] Readable
[[ -w FILE ]] Writable
[[ -x FILE ]] Executable
[[ f1 -nt f2 ]] f1 newer than f2
[[ f1 -ot f2 ]] f2 older than f1
[[ f1 -ef f2 ]] Same files

More conditions

Condition Description
[[ -o noclobber ]] If OPTION is enabled
[[ ! EXPR ]] Not
[[ X && Y ]] And
[[ X || Y ]] Or

logical and, or

if [ "$1" = 'y' -a $2 -gt 0 ]; then
    echo "The answer is YES"
fi


if [ "$1" = 'n' -o $2 -lt 0 ]; then
    echo "The answer is NO"
fi

Example

# Conditions with String
read -p "Enter the string: " STR
if [[ -z "$STR" ]]; then
    echo "The input String is empty"
elif [[ -n "$STR" ]]; then
    echo "The input String is not empty"
else
    echo "This condition will never happens"
fi


# Combinations
if [[ X && Y ]]; then
    # Logic here ...
fi


# Equal
read -p "Enter first string: " VAR1
read -p "Enter second string: " VAR2
if [[ "$VAR1" == "$VAR2" ]]; then
    # Your logic here ...
fi


# Regex
if [[ '1. abc' =~ ([a-z]+) ]]; then
    echo ${BASH_REMATCH[1]}
fi


# Smaller
if (( $VAR1 < $VAR2 )); then
   echo "$VAR1 is smaller than $VAR2"
fi


# Exists
if [[ -e "file.txt" ]]; then
    echo "file exists"
fi

# Loops in Bash


Basic for loop

for i in /etc/rc.*; do
    echo $i
done

C-like for loop

for ((i = 0 ; i < 200 ; i++)); do
    echo $i
done
# Output: 0 -> 199

Basic Ranges

for i in {1..5}; do
    echo "Welcome to bestforstudy.com: $i"
done

Ranges With step size

for i in {5..50..5}; do
    echo "Welcome to bestforstudy.com: $i"
done

Auto increment

i=1
while [[ $i -lt 10 ]]; do
    echo "Auto Increase index: $i"
    ((i++))
done
# Run this code to see the result ^^

Auto decrement

i=30
while [[ $i -gt 0 ]]; do
    echo "Auto decrement index: $i"
    ((i--))
done
# Run this code to see the result

# Functions in Bash


How to Define functions ?

firstFunc() {
    echo "hello $1"
}


# Same define as above (alternate syntax)
function firstFunc() {
    echo "hello $1"
}


firstFunc "bestforstudy.com"

Bash Returning values

yourFunc() {
    local yourResult='Your result will be here'
    echo $yourResult
}

result="$(yourFunc)"

Bash Raising errors

yourFunc() {
    return 1
}

if yourFunc; then
    echo "Success"
else
    echo "Fail"
fi

# Options In Bash


Options

# Avoid overlay files
# (echo "hi" > foo)
set -o noclobber


# Used to exit upon error
# avoiding cascading errors
set -o errexit   


# Unveils hidden failures
set -o pipefail  


# Exposes unset variables
set -o nounset

Glob Options

# Non-matching globs are removed  
# ('*.foo' => '')
shopt -s nullglob   


# Non-matching globs throw errors
shopt -s failglob  


# Case insensitive globs
shopt -s nocaseglob 


# Wildcards match dotfiles 
# ("*.sh" => ".foo.sh")
shopt -s dotglob    


# Allow ** for recursive matches 
# ('lib/**/*.rb' => 'lib/a/b/c.rb')
shopt -s globstar  

# History in Bash


Commands

Command Description
history Show history
shopt -s histverify Don't execute expanded result immediately

Expansions

Expression Description
!$ Expand last parameter of most recent command
!* Expand all parameters of most recent command
!-n Expand nth most recent command
!n Expand nth command in history
!<command> Expand most recent invocation of command <command>

Operations

Code Description
!! Execute last command again
!!:s/<FROM>/<TO>/ Replace first occurrence of <FROM> to <TO> in most recent command
!!:gs/<FROM>/<TO>/ Replace all occurrences of <FROM> to <TO> in most recent command
!$:t Expand only basename from last parameter of most recent command
!$:h Expand only directory from last parameter of most recent command

Slices

Code Description
!!:n Expand only nth token from most recent command (command is 0; first argument is 1)
!^ Expand first argument from most recent command
!$ Expand last token from most recent command
!!:n-m Expand range of tokens from most recent command
!!:n-$ Expand nth token to last from most recent command


Best Suggest