Home / Bash Shell Scripting Cheat Sheet for AlmaLinux, CentOS, and Ubuntu

Bash Shell Scripting Cheat Sheet for AlmaLinux, CentOS, and Ubuntu

Bash is by default installed on most Linux distributions like AlmaLinux, CentOS, Kali, and Ubuntu. The following cheat sheet outlines some important features of bash scripting.

Bash Script Header

#!/usr/bin/env bash
echo “Hello World”

Variables

#!/usr/bin/env bash
MSG=”Hello World”
echo “$MSG Albert” # Hello World Albert
echo ‘$MSG Albert # $MSG Albert

Strings

MSG=”hello world”

Replace

echo ${MSG/w/W} # hello World
echo ${MSG//[a-zA-Z]/X} # AAAAA AAAAA

Uppercase

echo ${MSG^} # Hello world
echo ${MSG^^} # HELLO WORLD
MSG=”HELLO WORLD”
echo ${MSG,} # hELLO WORLD
echo ${MSG,,} # hello world

Substring

echo ${MSG:0:5} # hello
echo ${MSG%world} # hello
echo ${MSG#hello} # world

Alternative

echo ${MSG:-val} # HELLO WORLD
echo ${FOO:-val} # val

Collections

Arrays

names=(‘Ben’ ‘Bolt’ ‘Bob’)
names+=(‘Soto’) # Appends element
unset names[3] # Removes element

echo ${names[0]} # Ben
echo ${names[@]} # Ben Bolt Bob
echo ${#names[@]} # 3

Maps

declare -a score
score[X]=”1″
score[Y]=”2″
score[Z]=”3″
unset score[X] # Delete X entry

echo ${!score[@]} # X Y Z
echo ${score[@]} # 2 1 3
echo ${#score[@]} # 3

Functions

helloworld() {
echo “Number of arguments $#” # 2
echo “Hello World $1 from $2” # Hello World Ben from Bash
}
helloworld “Ben” “Bash

helloworld() {
echo ‘My return string!’
}
msg=$(helloworld)
echo $msg

Conditionals

if [[ $b -gt 4 ]]; then
echo “$b is greater than 4”
elif [[ $b -lt 4 ]]; then
echo “$b less than 4”
else
echo “$b is equal 4”
fi

Numeric Conditions

[[ NUM -eq NUM ]] Equal
[[ NUM -ne NUM ]] Not equal
[[ NUM -lt NUM ]] Less than
[[ NUM -le NUM
a]]Less than or equal to
[[ NUM -gt NUM ]] [[ NUM -ge NUM ]] Greater than or equal to

String Conditions

[[ STRING
== STRING
]]Equal [[ STRING !=
STRING ]]Not Equal [[ -z STRING
]]Empty string [[ -n STRING
]]Not empty string [[ STRING
=~ STRING
]]Regular expression match

File Conditions

[[ -f FILE ]] Is a file [[ -d FILE ]] Is a directory [[ -e FILE ]] Exists [[ -r -w -x FILE ]] Is readable, Writable, executable [[ -h FILE ]] Is symbolic link

Boolean conditions

a|[[ ! EXPR ]] |Not
a|[[ BOOL && BOOL ]] |And
a|[[ BOOL || BOOL ]] |OR

Loops

For

for ((i = 0 ; i < 10 ; i++)); do
echo “Hello World $i”
done

for i in {1..5}; do
echo “Hello World $i”
done

While

x=1;
while [ $x -le 5 ]; do
echo “Hello World”
done

Files

for i in /tmp/*.txt; do
echo $i
done
cat /tmp/hello.txt | while read line; do
echo $line
done

Print Output

printf “nn@ Writing @n”

Read Input

echo -n “Type answer: “
read ans
echo $ans

Leave a Reply