0% found this document useful (0 votes)
19 views48 pages

(CC - 23) Lab 3

Uploaded by

salemaymen814
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)
19 views48 pages

(CC - 23) Lab 3

Uploaded by

salemaymen814
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/ 48

Cloud Computing

Lab 3
Bash Shell Scripting
Agenda

● What is Shell ? ● Bash Variables


● Shell Scripting ● Basic Operators
● Shell Classification ○ Arithmetic Operators
● Shell Types ○ Relational Operators
● What is Bash ? ○ String Operators
○ File Test Operators
● Bash Commands
○ Echo Command ● Bash Conditional Statements
○ Comments ● Bash Loops
○ Date and Time ● Bash Functions
○ Sleep
What is Shell ?

• Shell is an environment provided for the user to


interact with the machine.

• Shell is not an operating system (not a part of


Linux kernel).
• It is a way to interface with the operating system
and run commands.
• It uses the kernel to execute programs, create files,
…, etc.
What is Shell ?
• The terminal window in our computer contains a shell that
allows you to process information, store or retrieve data
and much more by interacting with a computer via
entering commands.
For example,
− Retrieving a list of files or
directories.
− Looking up today’s date and
time.
− Getting current directory
location.
− Making, copying or deleting
files.
Shell Scripting
• Shell scripting allows you to automate trivial tasks,
and to do things quickly.
• Shell scripting reduces extensive, complex, and
repetitive sequences of commands into a simple
command.
• You can put a set of commands in a plain text file with
the extension of .sh.
• The .sh files are shell scripts which can be
executed like normal commands.
Shell Classification
Command Line Shell Types
Bourne Shell (sh)
• This was one of the first shell programs that came with
Unix and are also the most widely used one.

• It was developed by Stephen Bourne.

• The ~/.profile file is used as a configuration file for sh.

• This is also the standard shell used for scripting.


Command Line Shell Types
C Shell (csh)
• The csh shell was developed by Bill Joy and modeled on
the C programming language.

• It was intended to improve interactivity with features such


as listing the command history and editing commands.

• The ~/.cshrc and the ~/.login files are used as


configuration files by csh.
Command Line Shell Types
Bourne Again Shell (bash)
• The bash shell was developed for the GNU project as a
replacement for sh.

• The basic features of bash are copied from sh, and also
adds some of the interactivity features from csh.

• The ~/.bashrc and the ~/.profile files are used as


configuration files by bash.
Command Line Shell Types
• Bash is a UNIX shell, a command interpreter and a
programming language.
o Command interpreter, it provides the user interface to
the GNU Core Utilities.
o Programming language features allow these utilities to
be combined.

• It’s the default open-source shell on many Linux and Mac


OS distributions today.

• We can write applications for Linux OS using Bash


commands.
Bash Script File
• Bash script file extension should be sh or the first line in
the file should be #!/bin/bash.

• For the bash file to be executed, the user should have


permissions to execute the script.
#!/bin/bash
• Sample run of the script:
# Script follows here:
sysadmin@localhost:~$ bash echo "What is your
name?"
test.sh
read PERSON
What is your name? echo "Hello, $PERSON“
Mohamed
Hello, Mohamed
sysadmin@localhost:~$ test.sh
Bash Echo Command
Bash Echo Command
echo [option(s)] [string]
• It writes its arguments to standard output:
test.sh
#!/bin/bash
echo "Hello World!"
echo -e "Hello\nWorld!"
echo -n "Hello World!"
sysadmin@localhost:~$ ./test.sh
Hello World!
Hello
World!
Hello World!sysadmin@localhost:~$
Bash Echo Command (Cont.)
test.sh
#!/bin/bash
# this is a single line comment in bash
echo First echo
<<MY_COMMENT
This is a multiple line comment
In Bash Scripting
MY_COMMENT
echo Second echo
sysadmin@localhost:~$ ./test.sh
First echo
Second echo
sysadmin@localhost:~$
Bash Variables
variableName=value
test.sh
#!/bin/bash
age=10 # number
ch='c' # character
str="Hello Bob!" # string
sysadmin@localhost:~$ ./
arr=("bash" "shell" "script") #
test.sh
array
Hello Bob! I am 10 years old
bash shell
echo $str "I am ${age} years old"
sysadmin@localhost:~$
echo "${arr[0]} ${arr[1]}"
Bash Variables (Cont.)
• Variables are case-sensitive. variableName=value
• There must be no space between variable name,
equal and value.

test.sh
#!/bin/bash

variable="It works" sysadmin@localhost:~$ ./test.sh


echo $variable It works
echo $Variable # Nothing will
appear test.sh: line 7: variable: command not
found
# Syntax error It works
variable ="It will not work" sysadmin@localhost:~$
echo $variable
Bash Variables (Cont.)
Special Variables
Variables Example
$0 The filename of the current script
n is a positive decimal number corresponding to the position of an
$n
argument (e.g., $1, $2, …, etc.)
$# The number of arguments supplied to a script
$* Stores all received arguments as a string (e.g., "${1} ${2}")
$@ Stores received arguments in a string array (e.g., ("${1}" "${2}"))
$? The exit status of the last command executed
$$ Represents the process ID number
Bash Variables (Cont.)
Special Variables - Example

#!/bin/bash sysadmin@localhost:~$ ./test.sh 10 15


echo "File Name: $0" File Name: ./test.sh
First Parameter : 10
echo "First Parameter : $1"
Second Parameter : 15
echo "Second Parameter : $2" Quoted Values: 10 15
echo "Quoted Values: $@" Quoted Values: 10 15
echo "Quoted Values: $*" Total Number of Parameters : 2
sysadmin@localhost:~$ echo $?
echo "Total Number of Parameters :
0
$#"
sysadmin@localhost:~$
Basic Operators
Arithmetic Operators
Operator Description
+ Adds values on either side of the operator
- Subtracts right hand operand from left hand operand
* Multiplies values on either side of the operator
/ Divides left hand operand by right hand operand
Divides left hand operand by right hand operand and returns
%
remainder
= Compares two numbers, if both are same then returns true
!= Compares two numbers, if both are different then returns true.
Basic Operators
• Any command written inside $( ) or ` ` will be
interpreted by the shell.
• $( COMMAND ) or ` COMMAND `  Expects any
shell command between brackets ( ) or
backquotes ` `
• $(( ))  Expects an expression between the
brackets (( ))
Basic Operators (Cont.)
Arithmetic Operators – With Integers
#!/bin/bash
num1=10
num2=5
# Using double parentheses $(( ))
result=$((num1 + num2))
echo $result
result=$((num1 - num2))
sysadmin@localhost:~$ ./test.sh
echo $result
15
result=$((num1 * num2)) 5
echo $result 50
result=$((num1 / num2)) 2
echo $result sysadmin@localhost:~$
Basic Operators (Cont.)
Arithmetic Operators – With Floating
Point
#!/bin/bash
num1=15.5
num2=40

# Bash bc command(floating point) sysadmin@localhost:~$ ./test.sh


add=$(echo "$num1+$num2" | bc) 15.5 + 40 equals 55.5
sub=$(echo "scale=4; $num1-$num2" | 15.5 - 40 equals -24.5
bc) 15.5 * 40 equals 620.0
multi=$(echo "scale=4; $num1*$num2" | 15.5 / 40 equals .3875
bc) sysadmin@localhost:~$
div=$(echo "scale=4; $num1/$num2" |
bc)

echo "$num1 + $num2 equals $add"


echo "$num1 - $num2 equals $sub"
Bash Date and Time
Date and Time date +<format-option(s)>

test.sh
#!/bin/bash
date
d=$(date +%m-%d-%Y)
sysadmin@localhost:~$ ./
echo $d test.sh
d=$(date '+%A %d-%B, %Y') Fri 03 Mar 2023 04:32:04 PM
echo $d EET
d=$(date +%m-%Y) 03-03-2023
echo $d Friday 03-March, 2023
03-2023
sysadmin@localhost:~$
Date and Time Formatting Options
date +%a Weekday Name of weekday in short (like Sun, Mon, Tue, Wed, Thu, Fri, Sat) Mon
date +%A Weekday Name of weekday in full (like Sunday, Monday, Tuesday) Monday
date +%b Month Name of Month in short (like Jan, Feb, Mar ) Jan
date +%B Month Month name in full (like January, February) January
date +%d Day Day of month (e.g., 01) 04
date +%D MM/DD/YY Current Date; shown in MM/DD/YY 02/18/18
date +%F YYYY-MM-DD Date; shown in YYYY-MM-DD 2018-01-19
date +%H Hour Hour in 24-hour clock format 18
date +%I Hour Hour in 12-hour clock format 10
date +%j Day Day of year (001..366) 152
date +%m Month Number of month (01..12) (01 is January) 05
date +%M Minutes Minutes (00..59) 52
date +%S Seconds Seconds (00..59) 18
date +%N Nanoseconds Nanoseconds (000000000..999999999) 300231695
date +%T HH:MM:SS Time as HH:MM:SS (Hours in 24 Format) 18:55:42
date +%u Day of Week Day of week (1..7); 1 is Monday 7
date +%U Week Displays week number of year, with Sunday as first day of week (00..53) 23
date +%Y Year Displays full year i.e. YYYY 2018
date +%Z Timezone Time zone abbreviation (Ex: IST, GMT) IST
Bash Sleep Command
Sleep Command sleep NUMBER[SUFFIX]
• Used to insert a delay or pause the execution for a
specified period.
• SUFFIX options: s (seconds), m (minutes), h (hours), d
(days)
test.sh
#!/bin/bash sysadmin@localhost:~$ ./
test.sh
echo HH:MM:SS HH:MM:SS
17:13:14/03-03-2023
echo $(date +%H:%M:%S/%m-%d-%Y) 17:13:18/03-03-2023
sleep 4 sysadmin@localhost:~$
echo $(date +%H:%M:%S/%m-%d-%Y)
Bash Conditional Statements
Bash IF
if [ expression ]
# ^ ^ ^ please note these
spaces
then
statement(s)
fi
Bash Conditional Statements (Cont.)
Bash IF
• For compound expressions, Observe that the condition has
double square brackets.
• You can use this syntax with any number of expressions

if [[ expression_1 && expression_2 ||


expression_3 ]]
then
statement(s)
fi
Bash Conditional Statements (Cont.)
Bash IF
test.sh
#!/bin/bash

# if condition is true
if [ "hello" == "hello" ]
then
sysadmin@localhost:~$ ./
echo "hello equals hello" test.sh
fi hello equals hello
sysadmin@localhost:~$
# if condition is false
if [[ "hello" == "bye" ]]; then
echo "hello equals bye"
fi
Bash Conditional Statements (Cont.)
Bash IF - Compare Numbers
• Relational Operators

Relational operation Operator Example


Equivalence -eq [ $a -eq $b ]
Less than -lt [ $a -lt $b ]
Less than or equal to -le [ $a -le $b ]
Greater than -gt [ $a -gt $b ]
Greater than or equal to -ge [ $a -ge $b ]
Does not equal -ne [ $a -ne $b ]
Bash Conditional Statements (Cont.)
Bash IF - Compare Numbers
test.sh
#!/bin/bash
a=10
b=20

if [ $a -eq $b ]; then
echo "$a -eq $b : a is equal to b"
sysadmin@localhost:~$ ./test.sh
else
echo "$a -eq $b: a is not equal to b" 10 -eq 20: a is not equal to b
fi
10 -gt 20: a is not greater
if [ $a -gt $b ]; then than b
echo "$a -gt $b: a is greater than b" sysadmin@localhost:~$
else
echo "$a -gt $b: a is not greater than
b"
Bash Conditional Statements (Cont.)
Operator Description
= or == Returns true if the value of two operands is equals
!= Returns true if the value of two operands is not equals
-z Returns true if length of the string is zero.
-n Returns true if length of the string non-zero.
-f Returns true if the file is existing.

if [ -f /etc/passwd ]
then
sysadmin@localhost:~$ ./
echo "passwd - File exists."
else test.sh
echo "passwd - File does not passwd - File exists.
exist." sysadmin@localhost:~$
fi
Bash Conditional Statements (Cont.)
Bash Else IF – elif
if <expression>; then
<commands>
elif <expression>; then
<commands>
else
<commands>
fi
Bash Conditional Statements (Cont.)
Bash IF - Compare Numbers
test.sh
#!/bin/bash
n=2

if [ $n -eq 1 ]; then
echo value of n is 1
elif [[ $n -eq 2 && $n -lt 5 ]]; then
echo value of n is less than threshold
fi
sysadmin@localhost:~$ ./test.sh
value of n is less than threshold
sysadmin@localhost:~$
Bash Conditional Statements (Cont.)
Bash Case
case EXPRESSION in
CASE1)
COMMAND-LIST
;;
CASE2)
COMMAND-LIST
;;

CASEN)
COMMAND-LIST
;;
*)
COMMAND-LIST
;;
esac
Bash Conditional Statements (Cont.)
Bash Case - Example
#!/bin/bash

time=15
case $time in
9)
echo Good Morning! sysadmin@localhost:~$ ./test.sh
;;
Good Day!
21)
echo Good Night!
sysadmin@localhost:~$
;;
*)
echo Good Day!
;;
esac
Bash Loops
Bash For Loop
• Allows iterating a specific set of statements over a
series of words in a string, elements in a sequence, or
elements in an array.
#!/bin/bash

# declare an array
arr=( "bash" "shell" "script" ) sysadmin@localhost:~$ ./test.sh
bash
# for loop that iterates over each shell
element in arr script
for i in "${arr[@]}" sysadmin@localhost:~$
do
echo $i
done
Bash Loops (Cont.)
Bash For Loop
• Bash For loop consider whitespaces in given string as word
separators.

#!/bin/bash

# declare a string
str="bash shell script" sysadmin@localhost:~$ ./test.sh
bash
# for loop that iterates over the shell
words script
for i in $str sysadmin@localhost:~$
do
echo $i
done
Bash Loops (Cont.)
Bash For Loop - Iterate Over a Sequence
• To iterate over a sequence of numbers.

sysadmin@localhost:~$ ./test.sh
#!/bin/bash 1
2
3
for i in $(seq 1 10) 4
5
do 6
echo $i 7
8
done 9
10
sysadmin@localhost:~$
Bash Loops (Cont.)
Bash For Loop - Use Counter to Iterate
Over Elements of Array
• To iterate over an array’s elements using a variable for counter
#!/bin/bash
arr=("bash" "shell" "script")

# get length of an array to a sysadmin@localhost:~$ ./test.sh


variable 1 : bash
arrlength=${#arr[@]} 2 : shell
3 : script
# for loop to read all values and sysadmin@localhost:~$
indexes
for ((i = 1; i < ${arrlength} + 1; i+
+)) do
echo $i " : " ${arr[$i - 1]}
Bash Loops (Cont.)
Bash For Loop – Break Command
• to break the for loop abruptly even before the for condition fails.
#!/bin/bash
arr=("apple" "orange" "lemon" "banana")

# for loop iterates over each element in


arr
for i in "${arr[@]}“
do sysadmin@localhost:~$ ./
echo $i test.sh
# break for loop based on a apple
orange
condition
lemon
if [ $i == "lemon" ]; then sysadmin@localhost:~$
break
Bash Loops (Cont.)
Bash While Loop
• Execute a block of statements repeatedly based on an
expression that evaluates to TRUE.
sysadmin@localhost:~$ ./test.sh
#!/bin/bash 0
count=10 1
i=0 2
3
4
while [ $i -lt $count ]
5
do 6
echo "$i" 7
i=$((i + 1)) 8
done 9
sysadmin@localhost:~$
Bash Loops (Cont.)
Bash While Loop – Multiple Conditions
• If the expression should have multiple conditions.
while [[ expression ]]; do
statement(s)
done
#!/bin/bash
count=10 ; a=0 ; b=0
sysadmin@localhost:~$ ./test.sh
while [[ $a -lt $count && $b -lt 0
4 ]] 1
do 2
echo "$a" 3
a=$((a + 1)) sysadmin@localhost:~$
b=$((b + 1))
done
Bash Loops (Cont.)
Bash Until Loop
• Execute a block of statements repeatedly based on an
expression that evaluates to TRUE.
sysadmin@localhost:~$ ./test.sh
#!/bin/bash 20
count=10 19
18
i=20 17
16
until [ $i -lt $count ] 15
do 14
echo "$i" 13
12
i=$((i + 1)) 11
done 10
Bash Functions
• Function must be defined in the shell script first,
before you can use it.
• Arguments could be passed to functions and
accessed inside the function as $1, $2 etc.
• Local Variables could be declared inside the
function and the scope of such local variables is
only that function.
function <function_name> <function_name> () {
{ # function body
# function body• or }
}
Bash Functions (Cont.)
Simple Function
test.sh
#!/bin/bash
sampleFunction() {
echo Hello from Sample Function.
}
sampleFunction
sysadmin@localhost:~$ ./test.sh
Hello from Sample Function.
Bash Functions (Cont.)
Simple Function with Arguments
test.sh
#!/bin/bash
# bash function example with arguments
function functionWithArgs {
echo $1 : $2 is $3 years old
}

functionWithArgs "$(date +"[%m-%d %H:%M:%S]")" "Ahmed"


"25"
sysadmin@localhost:~$ ./test.sh
[03-05 04:41:14] : Ahmed is 25 years old
Bash Functions (Cont.)
Bash Local Variables local variableName=value

test.sh
#!/bin/bash

SHELL="Unix" # bash variable

function bashShell { sysadmin@localhost:~$ ./test.sh


# bash local variable
local SHELL="Bash" Unix
echo $SHELL Bash
}
Unix
echo $SHELL sysadmin@localhost:~$
bashShell
echo $SHELL
Any Questions

You might also like