0% found this document useful (0 votes)
119 views103 pages

Learn Bash Quickly: Master Bash Scripting and Learn How To Automate Boring Linux Tasks

This document provides an overview of a course to learn Bash scripting. The course contains 10 modules that cover topics like Bash variables, arguments, arrays, arithmetic operations, and automating tasks. It also describes how to set up a Linux virtual machine for running the example scripts. Each module breaks down a topic into individual lessons and provides sample Bash scripts to demonstrate the concepts.

Uploaded by

test00
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views103 pages

Learn Bash Quickly: Master Bash Scripting and Learn How To Automate Boring Linux Tasks

This document provides an overview of a course to learn Bash scripting. The course contains 10 modules that cover topics like Bash variables, arguments, arrays, arithmetic operations, and automating tasks. It also describes how to set up a Linux virtual machine for running the example scripts. Each module breaks down a topic into individual lessons and provides sample Bash scripts to demonstrate the concepts.

Uploaded by

test00
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 103

Learn Bash Quickly

Master Bash Scripting and learn how to automate boring


Linux tasks.
Course Prerequisites
1. You know the basics of the Linux Command Line.

2. Basic Programming Knowledge would help a lot but is


NOT required.

3. You have a passion to learn.


Course Overview
Module 1: Hello Bash Module 6: Bash Strings

Module 2: Bash Variables Module 7: Decision Making


in Bash
Module 3: Bash Arguments
Module 8: Bash Loops
Module 4: Bash Arrays
Module 9: Bash Functions
Module 5: Bash Arithmetic
Operations Module 10: Automation
with Bash
Creating a Linux VM
1. You can create a Linux VM on VirtualBox.

2. You can create a Linux VM on VMware Fusion.

3. You can create a Linux VM on VMware Workstation Player.

4. You can create a Linux VM on any cloud service provider:


Azure, AWS, Google Cloud, Alibaba Cloud, Digital Ocean,
Oracle Cloud, etc.

5. You can use even use a Raspberry PI or a BeagleBone.


Module 1
elliot@allsafe:~$ cat module1.title
*************** Hello Bash **************
Module 1
elliot@allsafe:~$ cat module1.overview
-----------------------------------------
1. Create and Run your first Shell Script

2. Convert Your Shell Script into a Bash Script (shebang)

3. Editing Your PATH Variable

4. Adding Comments
-----------------------------------------
Create and Run your first Shell Script

elliot@allsafe:~$ cat steps.txt


-----------------------------------------

1. Create a new directory named scripts

2. Inside scripts, create a file named hello.sh

3. Edit the file hello.sh to contain the line:


echo ‘Hello, Friend!’

4. Run the script hello.sh

-----------------------------------------
Convert your Shell script into a Bash Script

elliot@allsafe:~$ cat steps.txt


-----------------------------------------

1. Insert the shebang line at the very beginning of your shell script:

#!/bin/bash

echo "Hello, Friend!"

2. Make your script executable (chmod u+x hello.sh)

3. Run your bash script.

-----------------------------------------
Editing your PATH variable

elliot@allsafe:~$ cat steps.txt


-----------------------------------------

1. Use the export command:

export PATH:$PATH:/home/elliot/scripts

to add your scripts directory to the PATH variable.

2. Run your script hello.sh

-----------------------------------------
Adding Comments

elliot@allsafe:~$ cat hello.sh

#!/bin/bash
# This is a comment
echo "Hello, Friend!" # This is a simple echo statement
Module 2
elliot@allsafe:~$ cat module2.title
************ Bash Variables ************
Module 2
elliot@allsafe:~$ cat module2.overview
-----------------------------------
1. Using variables in bash scripts

2. Variables and Data Types

3. Constant Variables

4. Command Substitutions

5. A Smarter "Hello, Friend!" Script


-----------------------------------
Using variables in bash scripts

elliot@allsafe:~$ cat hello.sh


#!/bin/bash

echo "What’s your name, stranger?"

read name

echo "Hello, $name!"


Variables and Data Types

elliot@allsafe:~$ cat variables.sh

age=27
age=23
letter=‘c’
color=‘blue’
year=2022
Constant Variables

elliot@allsafe:~$ readonly PI=3.14159


elliot@allsafe:~$ echo $PI
3.14159

elliot@allsafe:~$ PI=123
bash: PI: readonly variable

elliot@allsafe:~$ echo $PI


3.14159
Command Substitutions

elliot@allsafe:~$ TODAY=$(date)
elliot@allsafe:~$ echo $TODAY
Thu 17 Jun 2021 12:59:25 PM CST

elliot@allsafe:~$ TODAY=`date`
elliot@allsafe:~$ echo $date
Thu 17 Jun 2021 01:01:28 PM CST

variable=$(command)
variable=`command`
A Smarter “Hello, Friend!” Script

elliot@allsafe:~$ cat hello.sh

#!/bin/bash

echo "Hello, $(whoami)!"


Module 3
elliot@allsafe:~$ cat module3.title
************ Bash Arguments *************
Module 3
elliot@allsafe:~$ cat module3.overview
-----------------------------------
1. Passing one argument to a bash script

2. Passing multiple arguments to a bash script

3. Getting creative with arguments

4. Special bash variables


-----------------------------------
Passing one argument to a bash
script

elliot@allsafe:~$ cat count_lines.sh

#!/bin/bash

echo –n "Please enter a filename: "


read filename
nlines=$(wc -l < $filename)

echo "There are $nlines in $filename"


Passing one argument to a bash
script … Continued

elliot@allsafe:~$ cat count_lines.sh

#!/bin/bash

nlines=$(wc -l < $1)


echo "There are $nlines in $1"

elliot@allsafe:~$ ./count_lines.sh /etc/group


Passing multiple arguments to a
bash script
script.sh arg1 arg2 arg3 …

elliot@allsafe:~$ cat count_lines.sh

n1=$(wc -l < $1)


n2=$(wc -l < $2)
n3=$(wc -l < $3)

echo "There are $n1 lines in $1"


echo "There are $n2 lines in $2"
echo "There are $n3 lines in $3"

elliot@allsafe:~$ ./count_lines.sh /etc/passwd /etc/group /etc/hosts


Getting creative with
arguments
You can turn hard commands into a simple bash script! 

elliot@allsafe:~$ cat find.sh

#!/bin/bash

find / -iname $1 2> /dev/null

elliot@allsafe:~$ ./find.sh boot.log


Special Bash Variables
Special Variable Description

$0 The name of the bash script.

$1, $2 … $n The bash script arguments.

$$ The process id of the current shell.

$# The total number of arguments passed to the script.

$@ The value of all arguments passed to the script.

$? The exit status of the last executed command.

$! The process id of the last executed command.


Special Bash Variables
--- Continued

elliot@allsafe:~$ cat special.sh

echo "Name of the script: $0"

echo "Total number of arguments: $#"

echo "Values of all arguments: $@"


Module 4
elliot@allsafe:~$ cat module4.title
************** Bash Arrays *************
Module 4
elliot@allsafe:~$ cat module4.overview
-----------------------------------
1. Creating your first array

2. Accessing array elements

3. Adding array elements

4. Deleting array elements

5. Creating hybrid arrays


-----------------------------------
Creating your first array
elliot@allsafe:~$ cat timestamp.sh

#!/bin/bash

file1="f1.txt"
file2="f2.txt"
file3="f3.txt"
file4="f4.txt"
file5="f5.txt"

touch $file1 $file2 $file3 $file4 $file5


Creating your first array
--- Continued
array_name=(value1 value2 value3 …)

elliot@allsafe:~$ cat timestamp.sh

#!/bin/bash

files=("f1.txt" "f2.txt" "f3.txt" "f4.txt" "f5.txt")

… now we need to access the array elements! We will see in the next slide
Accessing array elements
elliot@allsafe:~$ cat reverse.sh

#!/bin/bash

files=("f1.txt" "f2.txt" "f3.txt" "f4.txt" "f5.txt")

echo ${files[4]} ${files[3]} ${files[2]} ${files[1]} ${files[0]}

elliot@allsafe:~$ ./reverse.sh
f5.txt f4.txt f3.txt f2.txt f1.txt
Accessing array elements
--- Continued
elliot@allsafe:~$ echo ${files[*]}

f1.txt f2.txt f3.txt f4.txt f5.txt

elliot@allsafe:~$ echo ${#files[@]}

elliot@allsafe:~$ files[0]="a.txt"
Adding array elements

elliot@allsafe:~$ cat distros.sh

#!/bin/bash
distros=("Ubuntu" "Red Hat" "Fedora")
echo ${distros[*]}
distros+=("Kali")
echo ${distros[*]}

elliot@allsafe:~$ ./distros.sh
Ubuntu Red Hat Fedora
Ubuntu Red Hat Fedora Kali
Deleting array elements
elliot@allsafe:~$ cat numbers.sh
#!/bin/bash

num=(1 2 3 4 5)
echo ${num[*]}
unset num[2]
echo ${num[*]}
unset num
echo ${num[*]}

elliot@allsafe:~$ ./numbers.sh
1 2 3 4 5
1 2 4 5
Creating hybrid arrays
elliot@allsafe:~$ cat user.sh
#!/bin/bash

user=("john" 122 "sudo,developers" "bash")

echo "User Name: ${user[0]}"


echo "User ID: ${user[1]}"
echo "User Groups: ${user[2]}"
echo "User Shell: ${user[3]}"
Module 5
elliot@allsafe:~$ cat module5.title
****** Basic Arithmetic Operations *******
Module 5
elliot@allsafe:~$ cat module5.overview
-----------------------------------
1. Addition and Subtraction

2. Multiplication and Division

3. Powers and Remainders

4. Celsius to Fahrenheit Calculator


-----------------------------------
Addition and Subtraction
elliot@allsafe:~$ cat addition.sh
#!/bin/bash

fs1=$(du –b $1 | cut –f1)


fs2=$(du –b $2 | cut –f1)

echo "File size of $1 is: $fs1 bytes"


echo "File size of $2 is: $fs2 bytes"

total=$(($fs1 + $fs2))

echo "Total size is: $total bytes"


Addition and Subtraction
--- Continued
elliot@allsafe:~$ ./addition.sh /etc/passwd /etc/group
File size of /etc/passwd is: 2795 bytes
File size of /etc/group is: 1065 bytes

Total size is: 3860 bytes

$((arithmetic-expression))
$((10-3)) ==> 7
Multiplication and Division

elliot@allsafe:~$ cat giga2mega.sh


#!/bin/bash

GIGA=$1
MEGA=$(($GIGA * 1024))

echo "$GIGA GB is equal to $MEGA MB"

elliot@allsafe:~$ ./giga2mega.sh 4
4 GB is equal to 4096 MB
Multiplication and Division
--- Continued
KILO=$(($GIGA * 1024 * 1024))

elliot@allsafe:~$ echo $(( 5 / 2 ))


2

elliot@allsafe:~$ echo "5/2" | bc -l


2.50000000000000000000

elliot@allsafe:~$ echo "2.5 * 3" | bc -l


7.5

elliot@allsafe:~$ echo "4.1 – 0.5" | bc -l


3.6
Powers and Remainders
elliot@allsafe:~$ cat power.sh
#!/bin/bash

a=$1
b=$2

result=$(($a**$b))
echo="$a^$b=$result"

elliot@allsafe:~$ ./power.sh 2 3
2^3=8
elliot@allsafe:~$ ./power.sh 3 2
3^2=9
elliot@allsafe:~$ ./power.sh 5 2
5^2=25
Powers and Remainders
--- Continued
rem=$(( 17 % 5 ))

elliot@allsafe:~$ echo $(( 17 % 5 ))


2

elliot@allsafe:~$ echo $(( 22 % 7 ))


1

elliot@allsafe:~$ echo $(( 97 % 9 ))


7
Celsius to Fahrenheit
Calculator
F = C x (9/5) + 32
elliot@allsafe:~$ cat c2f.sh
#!/bin/bash

C=$1
F=$(echo "scale=2; $C * (9/5) + 32" | bc –l)
echo "$C degrees Celsius is equal to $F degrees Fahrenheit."

elliot@allsafe:~$ ./c2f.sh 2
2 degrees Celsius is equal to 35.60 degrees Fahrenheit.
elliot@allsafe:~$ ./c2f.sh -3
-3 degrees Celsius is equal to 26.60 degrees Fahrenheit.
elliot@allsafe:~$ ./c2f.sh 27
27 degrees Celsius is equal to 80.60 degrees Fahrenheit.
Module 6
elliot@allsafe:~$ cat module6.title
************* Bash Strings ***************
Module 6
elliot@allsafe:~$ cat module6.overview
-----------------------------------
1. Get String Length

2. Concatenating Strings

3. Finding Substrings

4. Extracting Substrings

5. Replacing Substrings

6. Deleting Substrings

7. Converting uppercase and lowercase Letters


-----------------------------------
Get String Length
${#string}

elliot@allsafe:~$ distro="Ubuntu"

elliot@allsafe:~$ echo ${#distro}


6
Concatenating Strings
str3=$str1$str2

elliot@allsafe:~$ cat con.sh


#!/bin/bash

str1="Mr."
str2=" Robot"

str3=$str1$str2

echo $str3

elliot@allsafe:~$ ./con.sh
Mr. Robot
Finding Substrings
expr index string substr

elliot@allsafe:~$ str="Bash is Cool"

elliot@allsafe:~$ word="Cool"

elliot@allsafe:~$ expr index "$str" "$word"


9
Extracting Substrings
${string:begin:end}

elliot@allsafe:~$ foss="Fedora is a free operating system"

elliot@allsafe:~$ echo ${foss:0:6}


Fedora

elliot@allsafe:~$ echo ${foss:12}


free operating system
Replacing Substrings
${string/old/new}

elliot@allsafe:~$ foss="Fedora is a free operating system"

elliot@allsafe:~$ echo ${foss/Fedora/Ubuntu}


Ubuntu is a free operating system

elliot@allsafe:~$ echo ${foss/free/popular}


Fedora is a popular operating system
Deleting Substrings
${string/substr}
elliot@allsafe:~$ fact="Sun is a big star"
elliot@allsafe:~$ echo ${fact/big}
Sun is a star

elliot@allsafe:~$ cell="112-358-1321"
elliot@allsafe:~$ echo ${cell/-}
112358-1321

elliot@allsafe:~$ echo ${cell//-}


1123581321

elliot@allsafe:~$ cell=${cell//-}
Converting Uppercase
and Lowercase Letters
elliot@allsafe:~$ legend="john nash"
elliot@allsafe:~$ actor="JULIA ROBERTS"

elliot@allsafe:~$ echo ${legend^^}


JOHN NASH
elliot@allsafe:~$ echo ${actor,,}
julia roberts

elliot@allsafe:~$ echo ${legend^}


John nash
elliot@allsafe:~$ echo ${actor,}
jULIA ROBERTS

elliot@allsafe:~$ echo ${legend^^[jn]}


JohN Nash
Module 7
elliot@allsafe:~$ cat module7.title
******** Decision Making in Bash *********
Module 7
elliot@allsafe:~$ cat module7.overview
-----------------------------------
1. Using if statement

2. Using if-else statement

3. Using elif statement

4. Using nested if statements

5. Using case statement

6. Test conditions in bash


-----------------------------------
Using if statement
if [ condition ]; then
your code
fi

elliot@allsafe:~$ cat root.sh


#!/bin/bash

if [ $(whoami) = ‘root’ ]; then


echo "You are root"
fi

root@allsafe:~# ./root.sh
You are root
Using if-else statement
elliot@allsafe:~$ cat root.sh
#!/bin/bash

if [ $(whoami) = ‘root’ ]; then


echo "You are root"
else
echo "You are not root"
fi

root@allsafe:~# ./root.sh
You are root

elliot@allsafe:~$ ./root.sh
You are not root
Using elif statement
elliot@allsafe:~$ cat age.sh
#!/bin/bash

AGE=$1

if [ $AGE -lt 13 ]; then


echo "You are a Kid."
elif [ $AGE -lt 20 ]; then
echo "You are a teenager."
elif [ $AGE -lt 65 ]; then
echo "You are an adult."
else
echo "You are an elder."
fi
Using elif statement
… Continued
elliot@allsafe:~$ ./age.sh 11
You are a Kid.

elliot@allsafe:~$ ./age.sh 18
You are a teenager.

elliot@allsafe:~$ ./age.sh 44
You are an adult.

elliot@allsafe:~$ ./age.sh 70
You are an elder.
Using nested if statements
elliot@allsafe:~$ cat weather.sh
#!/bin/bash

TEMP=$1

if [ $TEMP -gt 5 ]; then


if [ $TEMP -lt 15 ]; then
echo "The weather is cold."
elif [ $TEMP -lt 25 ]; then
echo "The weather is nice."
else
echo "The weather is hot."
fi
else
echo "It’s Freezing outside …"
fi
Using nested if statements
… Continued
elliot@allsafe:~$ ./weather.sh 0
It’s Freezing outside …

elliot@allsafe:~$ ./weather.sh 8
The weather is cold.

elliot@allsafe:~$ ./weather.sh 16
The weather is nice.

elliot@allsafe:~$ ./weather.sh 30
The weather is hot.

elliot@allsafe:~$ ./weather.sh -20


It’s Freezing outside …
Using case statement

case expression in
pattern1 )
Commands ;;
pattern2 )
Commands ;;
pattern3 )
Commands ;;
* )
Commands ;;
esac
Using case statement
… Continued
elliot@allsafe:~$ cat char.sh
#!/bin/bash

CHAR=$1

case $CHAR in
[a-z])
echo "Small Alphabet." ;;
[A-Z])
echo "Big Alphabet." ;;
[0-9])
echo "Number." ;;
*)
echo "Special Character." ;;
esac
Using case statement
… Continued
elliot@allsafe:~$ ./char.sh a
Small Alphabet.

elliot@allsafe:~$./char.sh Z
Big Alphabet.

elliot@allsafe:~$./char.sh 4
Number.

elliot@allsafe:~$./char.sh $
Special Character.
Test Conditions in Bash
Condition Meaning

$a -lt $b $a < $b

$a -gt $b $a > $b

$a -le $b $a <= $b

$a -ge $b $a >= $b
$a is equal to $b
$a -eq $b
$a == $b
$a is NOT equal to $b
$a -ne $b
$a != $b
-e $FILE $FILE exists

-d $FILE $FILE exists and is a directory

-f $FILE $FILE exists and is a regular file

-L $FILE $FILE exists and is a soft link (symbolic)

$STRING1 = $STRING2 $STRING1 is equal to $STRING2

$STRING1 != $STRING2 $STRING1 is NOT equal to $STRING2

-z $STRING1 $STRING1 is empty


Test Conditions in Bash
--- Continued

elliot@allsafe:~$ man test


Test Conditions in Bash
--- Continued
elliot@allsafe:~$ cat filetype.sh
#!/bin/bash

if [ $# -ne 1 ]; then
echo "Error: Invalid number of arguments."
exit 1
fi

file=$1

if [ -f $file ]; then
echo "$file is a regular file."
elif [ -L $file ]; then
echo "$file is a soft link."
elif [ -d $file ]; then
echo "$file is a directory."
else
echo "$file does not exist."
fi
Test Conditions in Bash
--- Continued
elliot@allsafe:~$ ./filetype.sh
Error: Invalid number of arguments.

elliot@allsafe:~$ ./filetype.sh weather.sh


weather.sh is a regular file.

elliot@allsafe:~$ ./filetype.sh /bin


/bin is a soft link.

elliot@allsafe:~$ ./filetype.sh /var


/var is a directory.

elliot@allsafe:~$ ./filetype.sh blabla.txt


blabla.txt does not exist.
Module 8
elliot@allsafe:~$ cat module8.title
**************** Bash Loops *************
Module 8
elliot@allsafe:~$ cat module8.overview
-----------------------------------
1. For Loops in Bash
• C-Style for Loops
• List/Range for Loops

2. While Loops in Bash

3. Until Loops in Bash

4. Traversing Array Elements

5. Using break and continue statements

6. Infinite Loops in Bash


-----------------------------------
For Loops In Bash
** C-Style for loops **

for ((initialize; condition; increment)); do


[Commands]
done

elliot@allsafe:~$ cat for.sh


#!/bin/bash

for ((i=0; i < 10; i++)); do


echo "Hello, Friend $i!"
done
For Loops In Bash
** C-Style for loops **
… Continued

elliot@allsafe:~$ ./for.sh
Hello, Friend 0!
Hello, Friend 1!
Hello, Friend 2!
Hello, Friend 3!
Hello, Friend 4!
Hello, Friend 5!
Hello, Friend 6!
Hello, Friend 7!
Hello, Friend 8!
Hello, Friend 9!
For Loops In Bash
** List/Range for loops**

for item in [LIST]; do


[Commands]
done

for i in {0..9}; do
echo "Hello, Friend $i!"
done
For Loops In Bash
** List/Range for loops**
… Continued

elliot@allsafe:~$ cat var.sh elliot@allsafe:~$ ./var.sh


#!/bin/bash /var/backups
/var/cache
for i in /var/*; do /var/crash
echo $i /var/lib
done /var/local
/var/lock
/var/log
/var/mail
/var/opt
/var/run
/var/snap
/var/spool
/var/tmp
While Loops In Bash

while [ condition ]; do elliot@allsafe:~$ ./3x10.sh


[Commands] 3
done 6
9
elliot@allsafe:~$ cat 3x10.sh
12
#!/bin/bash
15
num=1 18
while [ $num -le 10 ]; do 21
echo $(($num * 3)) 24
num=$(($num+1)) 27
done 30
Until Loops In Bash

until [ condition ]; do elliot@allsafe:~$ ./3x10.sh


[Commands] 3
done 6
9
elliot@allsafe:~$ cat 3x10.sh
12
#!/bin/bash
15
num=1 18
until [ $num -gt 10 ]; do 21
echo $(($num * 3)) 24
num=$(($num+1)) 27
done 30
Traversing Array Elements

elliot@allsafe:~$ cat prime.sh elliot@allsafe:~$ ./prime.sh


#!/bin/bash 2
3
prime=(2 3 5 7 11 13 17 19 23 29) 5
7
for i in "${prime[@]}"; do 11
echo $i 13
done 17
19
23
29
Using break and continue statements

elliot@allsafe:~$ cat break.sh elliot@allsafe:~$ cat odd.sh


#!/bin/bash #!/bin/bash

for ((i=1; i<=10; i++)); do for ((i=0; i<=10; i++)); do


echo $i if [ $(( $i % 2 )) -eq 0 ]; then
if [ $i -eq 3 ]; then continue
break fi
fi echo $i
done done

elliot@allsafe:~$ ./break.sh elliot@allsafe:~$ ./odd.sh


1 1
2 3
3 5
7
9
Infinite Loops in Bash

for ((i=10; i>0;i++)); do for ((;;)); do


echo $i [Commands]
done done

for ((i=10; i>0;i--)); do while [ true ]; do


echo $i [Commands]
done done
Module 9
elliot@allsafe:~$ cat module9.title
************* Bash Functions *************
Module 9
elliot@allsafe:~$ cat module9.overview
-----------------------------------
1. Creating Functions in Bash

2. Returning Function Values

3. Passing Function Arguments

4. Local and Global Variables

5. Recursive Functions
-----------------------------------
Creating Functions
in Bash
elliot@allsafe:~$ cat fun.sh
#!/bin/bash
function_name () {
Commands hello () {
} echo "Hello, Friend!"
}

hello
hello
function function_name() { hello
Commands
} elliot@allsafe:~$ ./fun.sh
Hello, Friend!
Hello, Friend!
Hello, Friend!
Returning Function Values
elliot@allsafe:~$ cat error.sh
#!/bin/bash

error() {
blabla
return 0
}

error
echo "The exit status of the error function is: $?"
Returning Function Values
… Continued
elliot@allsafe:~$ ./error.sh
./error.sh: line 4: blabla: command not found
The exit status of the error function is: 0
Passing Function Arguments
elliot@allsafe:~$ cat iseven.sh elliot@allsafe:~$ ./iseven.sh
#!/bin/bash 3 is odd.
4 is even.
iseven () { 20 is even.
if [ $(( $1 % 2 )) -eq 0 ]; then 111 is odd.
echo "$1 is even."
else
echo "$1 is odd."
fi
}

iseven 3
iseven 4
iseven 20
iseven 111
Passing Function Arguments
… Continued
elliot@allsafe:~$ cat funarg.sh
#!/bin/bash

fun() {
echo "$1 is the first argument to fun()"
echo "$2 is the second argument to fun()"
}

echo "$1 is the first argument to the script."


echo "$2 is the second argument to the script."

fun Yes 7
Passing Function Arguments
… Continued
elliot@allsafe:~$ ./funarg.sh Cool Stuff
Cool is the first argument to the script.
Stuff is the second argument to the script.
Yes is the first argument to fun()
7 is the second argument to fun()
Local and Global Variables

elliot@allsafe:~$ cat scope.sh


#!/bin/bash

v1='A'
v2='B'

myfun() {
local v1='C'
v2='D'
echo "Inside myfun(): v1: $v1, v2: $v2"
}

echo "Before calling myfun(): v1: $v1, v2: $v2"


myfun
echo "After calling myfun(): v1: $v1, v2: $v2"
Local and Global Variables
… Continued
elliot@allsafe:~$ ./scope.sh
Before calling myfun(): v1: A, v2: B
Inside myfun(): v1: C, v2: D
After calling myfun(): v1: A, v2: D
Recursive Functions
factorial(n) = n x factorial(n-1)

elliot@allsafe:~$ cat factorial.sh elliot@allsafe:~$ ./factorial.sh


#!/bin/bash 4! is: 24
5! is: 120
factorial() { 6! is: 720
if [ $1 -le 1 ]; then
echo 1
else
last=$(factorial $(( $1 - 1 )))
echo $(( $1 * last))
fi 4 x factorial(3)
} 4 x (3 x factorial(2))
4 x (3 x (2 x factorial(1)))
echo -n "4! is: " 4 x ( 3 x ( 2 x (1))) = 24
factorial 4
echo -n "5! is: "
factorial 5
echo -n "6! is: "
factorial 6
Module 10
elliot@allsafe:~$ cat module10.title
********* Automation with Bash **********
Module 10
elliot@allsafe:~$ cat module10.overview
-----------------------------------
1. Automating User Management

2. Automating Backups

3. Monitoring Disk Space


-----------------------------------
Automating User Management
elliot@allsafe:~$ cat adduser.sh
#!/bin/bash

servers=$(cat inventory.txt)

echo -n "Enter the username: "


read usrname
echo -n "Enter the user id: "
read uid

for i in $servers; do
echo $i
ssh $i "sudo useradd -m -u $uid $usrname"
if [ $? -eq 0 ]; then
echo "User $usrname is added successfully on $i"
else
echo "Error on $i"
fi
done
Automating User Management
… Continued
elliot@allsafe:~$ ./adduser.sh
Enter the username: ansible
Enter the user id: 777
webserver1
User ansible is added successfully on webserver1
webserver2
User ansible is added successfully on webserver2
webserver3
User ansible is added successfully on webserver3
webserver4
User ansible is added successfully on webserver4
webserver5
User ansible is added successfully on webserver5
Automating Backups
elliot@allsafe:~$ cat backup.sh #cleanup /tmp
#!/bin/bash sudo rm /tmp/*.gz

backup_dirs=("/etc" "/home" "/boot") echo "Backup script is done."


dest_dir="/backup"
dest_server="bkserver1"
backup_date=$(date +%b-%d-%y)

echo "Starting backup of: ${backup_dirs[@]}"

for i in "${backup_dirs[@]}"; do
sudo tar -Pczf /tmp/$i-$backup_date.tar.gz $i
if [ $? -eq 0 ]; then
echo "$i backup succeeded."
else
echo "$i backup failed."
fi
scp /tmp/$i-$backup_date.tar.gz $dest_server:$dest_dir
if [ $? -eq 0 ]; then
echo "$i backup transfer succeeded."
else
echo "$i backup transfer failed."
fi
done
Automating Backups
... Continued
elliot@allsafe:~$ ./backup.sh
Starting backup of: /etc /home /boot
/etc backup succeeded.
etc-Jun-20-21.tar.gz 100% 526KB 50.3MB/s 00:02
/etc backup transfer succeeded.
/home backup succeeded.
home-Jun-20-21.tar.gz 100% 5840 11.0MB/s 00:04
/home backup transfer succeeded.
/boot backup succeeded.
boot-Jun-20-21.tar.gz 100% 39MB 67.4MB/s 03:26
/boot backup transfer succeeded.
Backup script is done.

elliot@allsafe:~$ crontab –e
crontab: installing new crontab
elliot@allsafe:~$ crontab -l
0 0 * * * /home/elliot/scripts/backup.sh
Monitoring Disk Space

elliot@allsafe:~$ df -h / /apps /database


Filesystem Size Used Avail Use% Mounted on
/dev/root 29G 1.6G 28G 6% /
/dev/mapper/vg1-applv 4.9G 20M 4.6G 1% /apps
/dev/mapper/vg1-dblv 4.9G 4.4G 280M 95% /database
Monitoring Disk Space
… Continued
elliot@allsafe:~$ cat disk_space.sh
#!/bin/bash

filesystems=("/" "/apps" "/database")

for i in ${filesystems[@]}; do
usage=$(df -h $i | tail -n 1 | awk '{print $5}' | cut -d % -f1)
if [ $usage -ge 90 ]; then
alert="Running out of space on $i, Usage is: $usage%"
echo "Sending out a disk space alert email."
echo $alert | mail -s "$i is $usage% full" [email protected]
fi
done
Bonus: Debugging your Bash
Scripts (ALL)
elliot@allsafe:~$ cat giga2mega.sh
#!/bin/bash -x

GIGA=$1
MEGA=$(( $GIGA * 1024))

echo "$GIGA GB is equal to $MEGA MB“

elliot@allsafe:~$ bash -x giga2mega.sh 7


+ GIGA=7
+ MEGA=7168
+ echo '7 GB is equal to 7168 MB'
7 GB is equal to 7168 MB
Bonus: Debugging your Bash
Scripts (Part)
elliot@allsafe:~$ cat giga2mega.sh
#!/bin/bash

GIGA=$1
set -x # activate debugging from here
MEGA=$(( $GIGA * 1024))
set +x # stop debugging from here
echo "$GIGA GB is equal to $MEGA MB“

elliot@allsafe:~$ giga2mega.sh 4
+ MEGA=4096
+ set +x
4 GB is equal to 4096 MB
Bonus: Running a Bash Script
from Another One!
elliot@allsafe:~$ cat first.sh
#!/bin/bash
echo "Running the first script ..." && sleep 1
second.sh

elliot@allsafe:~$ cat second.sh


#!/bin/bash
echo "Running the second script ..." && sleep 1
third.sh

elliot@allsafe:~$ cat third.sh


#!/bin/bash
echo "Running the third script ..." && sleep 1
What to do next?

1. Apply what you have learned in your daily routine/tasks.

2. Learn other automation tools like Ansible or Puppet.

3. Learn a programming language like Python or Golang.

4. Learn more Linux skills.

5. Learn Azure/AWS Cloud.


An Advice from the heart.

Don’t follow trending skills; instead, think


about what you like to do and do it and
trust me; you will live a better life.

It’s story time!



echo “Farewell”

elliot@allsafe:~$ echo "Thank You"


Thank You

You might also like