Main Menu

Bash Scripting Cheat Sheet

This Bash Scripting cheat sheet contains basic and intermediate Bash Shell scripts. This article is intended for both novices and working professionals to get a quick reference about different bash scripts.

Bash (Bourne Again Shell) is a command-line shell software. Brian Fox created it as an improved version of the Bourne Shell. It is a GNU open-source project. Let’s look at a few examples to get a quick reference to bash scripting.

For more information about bash scripts, you can check out our previous article here.

Creating a variable and printing it on the terminal

name="Linux"
echo "Hello $name!"

Use shell commands in bash scripts

echo "Current directory is $(pwd)"
echo "Current directory is `pwd`"

Conditional execution of script

if [[ "$condition1" ]]; then
  echo "Condition 1 satisfied"
elif [[ "$condition2" ]]; then
  echo "Condition 2 satisfied"
fi

if (( $x < $y )); then
  echo "$x is smaller than $y"
fi

if [[ "$s1" == "$s2" ]]  #if two strings are equal

Comments in bash

# It is a comment

: '
This is
multi line
comment
'

User input

read var
echo "You entered $var"

Arithmetic operations in bash

read a b
sum=$((a+b))
diff=$((a-b))
echo "Sum is $sum and difference is $diff"

Functions in Bash Scripting

get_value() {
  echo "2"
}
echo "Value is $(get_value)"

function myfunc() {
    echo "I am called"
}

Ways to print variables

NAME="Linux"
echo $NAME
echo "$NAME"
echo "${NAME}!"

Arrays in Bash

arr=(1 2 3)
val=${arr[1]}
echo "Element at index 1 is $val"


arr=('X' 'Y' 'Z')
arr=("${arr[@]}" "A")    # Push an item
arr+=('A')                  # Push an item
unset arr[2]                         # Remove one item
arr=("${arr[@]}" "${arr2[@]}") # Concatenate with another array

echo ${arr[0]}           # Element #0
echo ${arr[-1]}          # Last element
echo ${#arr[@]}          # Number of elements

for i in "${arr[@]}"; do   #iterate through the array
  echo $i
done

Strings in Bash

VAR1='Hello Linux'
echo  $VAR1

name="Linux"
echo ${name}
echo ${name:0:2}    #=> "Li" (slicing the indices)
echo ${name::2}     #=> "Li" (slicing the indices)
echo ${name::-1}    #=> "Lin" (slicing the indices)
echo ${name:(-1)}   #=> "x" (slicing the from right)
echo ${name:(-2):1} #=> "u" (slicing the indices from right)

STR="LINUX"
echo ${STR,,}  #=> "linux" (all become lowercase letters)

STR="linux"
echo ${STR^^}  #=> "LINUX" (all become uppercase uppercase)

${#str}  #length of $str

Loops in Bash

for ((i = 0 ; i < 10 ; i++)); do
  echo $i
done

while true; do
  ···
done

for i in {0..10}; do
    echo "We are on $i"
done

for i in {0..10..2}; do  #loop using step size of 2
    echo "We are on $i"
done

Maintaining system

apt-get update
apt-get -y upgrade
apt-get -y autoremove
apt-get autoclean

Category: Tutorials Linux

Write Comment