Bash Basics

General Tips

Always start script with #!/bin/bash Give the script run permissions using chmod +x script.sh Each line is a new command that will be ran


Variables

Variables can be set using:

varname=value

Variables can be retrieved using $varname:

name="f1shh"
echo "My name is $name"

Script parameters

Parameters are stored in variables $1, $2, $3, ... To get the number of parameters, use $#

User Input

User input can be taken using the read varname command and the value taken can be retrieved like any other variable using $varname. EX:

echo "What is your favorite food"
read food
echo "You said you like: $food"

Arrays

Arrays in Bash are 0 indexed. You can create an array using arrayname=('elm1' 'elm2' 'elm3' 'elm4') You can then access an element of the array with $arrayname[index]

If you want to print out all elements of the array, you can do so with: echo "${arrayname[@]}"

if we want to remove or update a element in the array, we can do unset arrayname[index] or arrayname[index]='value'

Array Cheatsheet:

arrayname=('elm1' 'elm2' 'elm3' 'elm4')

echo $arrayname[1]
echo "{$arrayname[@]}"

arrayname[2]="UpdatedValue"
echo $arrayname[2]

unset arrayname[3]
echo "{$arrayname[@]}"

Conditionals

Stolen From TryHackMe: https://tryhackme.com/room/bashscripting

Operator
Description

-eq or =

Checks if the value of two operands are equal or not; if yes, then the condition becomes true.

-ne

Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true.

-gt

Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true.

-lt

Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true.

-ge

Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true.

number = 100
if [$number -ge 50]
then
	echo 'The number is greater then 50'
else
	echo 'the number is less then 50'
fi

You can check multiple conditions using:

number = 100
if [$number = 25] || [$number -gt 50]
then
	echo 'The number is 25 or greater then 50'
else
	echo 'the number is not 25 or is less then 50'
fi

For Loops

Loop through an range of values with:

# Prints out values 1-5
for n in {1..5}; 
do
    echo $n
done

Or you can use a more familiar style:

n=25
for (( i=1 ; i<=$n ; i++ )); 
do
    echo $i
done

Loop through an array:

arrayname=("elm1" "elm2" "elm3") 
for n in ${arrayname[@]}; 
do
    echo $n
done

Infinite Loop taken from: https://www.geeksforgeeks.org/bash-scripting-for-loop/

n=4
for (( ; ; )); 
do
    if [ $n -eq 9 ];then
        break
    fi
    echo $n
    ((n=n+1))
done

Last updated