Cheat Sheet For Bash Scripting

Cheat Sheet For Bash Scripting

This Bash scripting cheat sheet covers basic and intermediate Bash shell scripts. This article is intended for both newbies and working professionals to get a quick reference about various bash scripts. Bash (Bourne Again Shell) is a command-line shell software. Brian Fox developed it as an improved version of the Bourne shell. It is a GNU open source project. Let’s find out a few examples to get a quick reference to bash scripting. You can check our previous article here for more information about bash scripts.

Creating a variable and printing it to the terminal

name="linux"
echo "Hello $name!"

Use shell commands

Cheat Sheet 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

read more about the Nmap command here. Buy VPS from here.

Scroll to Top