SlideShare a Scribd company logo
UNIT 5
Branching Control Structures,
Loop-Control Structure, and
Continue and break Statements,
Expressions,
Command Substitution,
Command Line Arguments and
Functions.
Branching Control Structures
• Branching control structures allow you to control the flow of execution based
on certain conditions. The main branching control structures in shell
scripting are:
• if-else statements: These statements evaluate a condition and execute
one block of code if the condition is true, and another block of code if the
condition is false.
• case statements: Also known as switch statements in other programming
languages, case statements provide multiple conditional branches based on
the value of a variable.
Examples
#!/bin/bash
# Example script to check if a number is even or odd
echo "Enter a number:"
read number
if [ $((number % 2)) -eq 0 ]; then
echo "$number is even."
else
echo "$number is odd."
fi
OUTPUT:
Enter a number:
7
7 is odd.
Examples
#!/bin/bash
# Example script to determine the day of the
week based on a number
echo "Enter a number (1-7):"
read day
case $day in
1)
echo "Monday"
;;
2)
echo "Tuesday"
;;
3)
echo "Wednesday"
;;
4)
echo "Thursday"
;;
5)
echo "Friday"
;;
6)
echo "Saturday"
;;
7)
echo "Sunday"
;;
*)
echo "Invalid input. Please enter a number
between 1 and 7."
;;
esac
OUTPUT:
Enter a number (1-7):
3
Wednesday
Loop-Control Structure
• Loop-control structures allow you to execute a block of code
repeatedly until a certain condition is met. The main loop-control
structures in shell scripting are:
• for loops: These loops iterate over a sequence of values or
elements.
• while loops: These loops execute a block of code repeatedly as
long as a specified condition is true.
• until loops: These loops execute a block of code repeatedly until
a specified condition becomes true.
FOR
• A for loop construct can be used to execute a set of statements repeatedly as
long as a given condition is true.
• Here, expr1 contains initialization statement expr2 contains limit test
expression expr3 contains updating expression
• Firstly, expr1 is evaluated. It is executed only once.
• Then, expr2 is evaluated to true or false.
• If expr2 is evaluated to false, the control comes out of the loop w/o executing
the body of the loop.
• If expr2 is evaluated to true, the body of the loop (i.e. statement1) is executed.
• After executing the body of the loop, expr3 is evaluated.
• Then expr2 is again evaluated to true or false. This cycle continues until
expression becomes false.
Syntax:
for(expr1;expr2;expr3)
{
statement1;
}
EXAMPLE
#!/bin/sh
for i in 1 2 3 4 5
do
echo “welcome $i times”
done
OUTPUT
Iterate over all files in the current directory
#!/bin/bash
# Iterate over all files in the current directory
for file in *; do
echo "Processing file: $file"
done OUTPUT:
Processing file: file1.txt
Processing file: file2.txt
Processing file: directory
Nested loop
#!/bin/bash
# Nested loop example
for (( i=1; i<=3; i++ )); do
echo "Outer loop iteration: $i"
for (( j=1; j<=2; j++ )); do
echo "Inner loop iteration: $j"
done
done
OUTPUT:
Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2
WHILE
SYNTAX:
while (expression)
{
statement1
}
• A while loop construct can be used to execute a set of
statements repeatedly as long as a given condition is true.
• Firstly, the expression is evaluated to true or false.
• If expression is evaluated to false, the control comes out of the
loop w/o executing the body of loop.
• If the expression is evaluated to true, the body of the loop is
executed.
• After executing the body of the loop, the expression is again
evaluated to true or false. This cycle continues until expression
becomes false.
EXAMPLE
}
OUTPUT
#!/bin/sh
a=0
while [$a –lt 10]
do
echo “$a”
a=$(($a+1))
done
#!/bin/bash
# Prompt the user to enter a number
echo "Enter a number (0 to exit):"
# Initialize the variable to store user input
number=1
# Execute the loop until the user enters 0
while [ $number -ne 0 ]; do
read -r number
echo "You entered: $number"
done
• echo "Exiting the loop "
OUTPUT:
Enter a number (0 to exit):
5
You entered: 5
10
You entered: 10
0
You entered: 0
Exiting the loop.
Reading user input until a specific condition is met
#!/bin/bash
# Prompt the user to enter the length of the Fibonacci sequence
echo "Enter the length of the Fibonacci sequence:“
# Read the user input
read -r length
# Initialize variables for Fibonacci sequence
a=0
b=1
count=1
Generating a Fibonacci sequence
# Execute the loop to generate the Fibonacci sequence
echo "Fibonacci sequence:“
while [ $count -le $length ]; do
echo -n "$a "
fn=$((a + b))
a=$b
b=$fn
((count++))
Done
echo "" # Print a newline after the sequence
OUTPUT:
Enter the length of the Fibonacci sequence:
8
Fibonacci sequence:
0 1 1 2 3 5 8 13
Until Loop
• In an "until" loop, the loop continues executing the code
block until the specified condition evaluates to true.
• It is essentially the opposite of a "while" loop.
• Syntax:
until [ condition ]; do
# Code to be executed as long as the condition is false
done
UNTIL LOOP
#!/bin/bash
counter=0
until [ $counter -eq 5 ]; do
echo "Counter: $counter"
((counter++))
done
echo "Loop finished."
OUTPUT:
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Loop finished.
Squares using Until Loop
#!/bin/bash
target=10
current=1
until [ $current -ge $target ]; do
echo "Current Value: $current"
((current *= 2))
done
echo "Loop finished."
OUTPUT:
Current Value: 1
Current Value: 2
Current Value: 4
Current Value: 8
Loop finished.
Continue and break Statements
• These statements are used within loops to control the
flow of execution.
• continue: This statement causes the loop to skip the
rest of the current iteration and move to the next
iteration.
• break: This statement causes the loop to terminate
immediately, regardless of the loop's condition.
CONTINUE STATEMENTS
• The continue statement is similar to the break command, except that it
causes the current iteration of the loop to exit, rather than the entire
loop.
• This statement is useful when an error has occurred but you want to try
to execute the next iteration of the loop.
• Syntax:
continue [n]
//if n is mentioned then it continues from the nth enclosing loop.
Example
#!/bin/sh
for i in $(seq 1 5)
do
if (($i==3))
then
continue
fi
echo $i
done
OUTPUT:
1
2
4
5
Print even numbers between 1 and 10,
skipping odd numbers
#!/bin/bash
echo "Even numbers between 1 and 10:“
for ((i = 1; i <= 10; i++)); do
# Check if the number is odd
if [ $((i % 2)) -ne 0 ]; then
# Skip to the next iteration if the number is odd
continue
fi
# Print the even number
echo "$i"
OUTPUT:
Even numbers between 1 and 10:
2
4
6
8
10
BREAK STATEMENT
• The break statement is used to terminate the execution of the entire loop,
after completing the execution of all of the lines of code up to the break
statement.
• It then steps down to the code following the end of the loop.
• Syntax:
break [n]
// n is number of nested loops .
// By default the value of n is 1.
Example
#!/bin/sh
for i in $(seq 1 10)
do
if (($i==5))
then
break
fi
echo $i
done
OUTPUT:
1
2
3
4
Find the first negative number in a list of numbers
#!/bin/bash
echo "Finding the first negative number in the list:"
numbers=(5 10 -3 8 -6 2 4)
for num in "${numbers[@]}"; do
# Check if the number is negative
if [ $num -lt 0 ]; then
# Print the first negative number and exit the loop
echo "The first negative number is: $num"
break
fi
done
OUTPUT:
Finding the first negative number in the list:
The first negative number is: -3
Expressions
• Expressions in shell scripting are
combinations of operators, variables, and
values that evaluate to a single value.
• They are commonly used in conditions and
assignments.
Arithmetic Expressions
#!/bin/bash
result=$((10 + 5 * 2))
echo "Result of arithmetic expression: $result"
OUTPUT:
Result of arithmetic expression: 20
String Concatenation
#!/bin/bash
greeting="Hello"
name="John“
message="$greeting, $name!"
echo "$message"
OUTPUT:
Hello, John!
Comparison Expressions
#!/bin/bash
value1=10
value2=20
if [ $value1 -eq $value2 ]; then
echo "Values are equal"
else
echo "Values are not equal"
fi
OUTPUT:
Values are not equal
Logical Expressions
#!/bin/bash
age=25
if [ $age -ge 18 ] && [ $age -lt 60 ];
then
echo "You are an adult"
else
echo "You are not an adult"
fi
OUTPUT:
You are an adult
Command Substitution
• Command substitution allows you to use the
output of a command as part of another command
or expression.
• It can be done using backticks (`) or the $() syntax.
Basic Command Substitution
#!/bin/bash
current_date=$(date)
echo "Current date and time: $current_date"
OUTPUT:
Current date and time: <current_date_and_time>
Using Command Output in a Loop
#!/bin/bash
echo "Files in the current directory:"
for file in $(ls); do
echo "$file"
done
OUTPUT:
Files in the current directory:
file1.txt
file2.txt
directory
Command Substitution with Pipe
#!/bin/bash
# Command substitution with pipe example
cpu_info=$(cat /proc/cpuinfo | grep "model name" | uniq)
echo "CPU information: $cpu_info"
OUTPUT:
CPU information: model name : Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
Command Substitution in Arithmetic Expression
#!/bin/bash
total_files=$(ls | wc -l)
echo "Total number of files in the current directory:
$total_files"
OUTPUT:
Total number of files in the current directory: <number_of_files>
Command Line Arguments
• Command line arguments are values provided to a script
or program when it is executed from the command line.
• They can be accessed within the script using special
variables like $1, $2, etc., which represent the first,
second, and subsequent arguments passed to the script.
Basic Command Line Argument
#!/bin/bash
echo "First argument: $1"
OUTPUT:
./script.sh hello
First argument: hello
Multiple Command Line Arguments
#!/bin/bash
echo "First argument: $1"
echo "Second argument: $2"
echo "Third argument: $3"
OUTPUT:
./script.sh hello world 123
First argument: hello
Second argument: world
Third argument: 123
Using Command Line Arguments in a Loop
#!/bin/bash
echo "Command line arguments:“
for arg in "$@"; do
echo "$arg"
done
OUTPUT:
./script.sh one two three
Command line arguments:
one
two
three
Arithmetic Operation with Command Line
Arguments
#!/bin/bash
result=$(( $1 + $2 ))
echo "Sum of $1 and $2 is: $result"
OUTPUT:
./script.sh 5 10
Sum of 5 and 10 is: 15
Functions
• Functions in shell scripting allow you to encapsulate
blocks of code for reuse.
• They are defined using the function keyword or by
simply declaring them with their names followed by
parentheses.
• Functions can take arguments and return values.
Basic Function
#!/bin/bash
greet() {
echo "Hello, World!"
}
# Call the function
greet
OUTPUT:
Hello, World!
Function with Parameters
#!/bin/bash
greet() {
echo "Hello, $1!"
}
# Call the function with an argument
greet "John"
OUTPUT:
Hello, John!
Function with Return Value
#!/bin/bash
add() {
result=$(( $1 + $2 ))
echo $result
}
# Call the function and store the result in a variable
sum=$(add 5 10)
echo "Sum: $sum"
OUTPUT:
Sum: 15
Function with Local Variables
#!/bin/bash
calculate() {
local a=5
local b=10
local result=$(( a * b ))
echo "Result inside function: $result"
}
# Call the function
calculate
OUTPUT:
Result inside function: 50
Function Calling Another Function
#!/bin/bash
say_hello() {
echo "Hello!"
}
say_goodbye() {
echo "Goodbye!"
}
greet() {
say_hello
say_goodbye
}
• # Call the parent function
OUTPUT:
Hello!
Goodbye!
Recursive Function
#!/bin/bash
factorial() {
if [ $1 -eq 1 ]; then
echo 1
else
local prev=$(factorial $(( $1 - 1 )))
echo $(( $1 * prev ))
fi
}
# Calculate factorial of 5
result=$(factorial 5)
echo "Factorial of 5 is: $result"
OUTPUT:
Factorial of 5 is: 120
Function with Default Parameter
#!/bin/bash
greet() {
name=${1:-"World"}
echo "Hello, $name!"
}
# Call the function with and without argument
greet
greet "John"
OUTPUT:
Hello, World!
Hello, John!
Function Returning Multiple Values
#!/bin/bash
get_system_info() {
os=$(uname -s)
kernel=$(uname -r)
echo "$os $kernel"
}
# Call the function and store the result in variables
info=$(get_system_info)
echo "System information: $info"
OUTPUT:
System information: Linux 5.4.0-91-generic
Function with Error Handling
#!/bin/bash
divide() {
if [ $2 -eq 0 ]; then
echo "Error: Division by zero"
exit 1
fi
result=$(( $1 / $2 ))
echo "Result: $result"
}
# Call the function with different arguments
divide 10 2
divide 10 0
OUTPUT:
Result: 5
Error: Division by zero
Practice Programs
• Write a shell script that uses a for loop to print the multiplication table of a given
number.
• Create a script that iterates over a list of cities and prints a welcome message
for each city.
• Create a script that prompts the user for three numbers and prints their average
using a for loop.
• Write a shell script that displays the calendar for each month of a given year
using a for loop.
• Create a script that generates a random password of a specified length using a
for loop.
• Write a shell script that calculates the sum of digits of a given number using a
while loop.
• Create a script that reads numbers from the user until a negative number is
entered, then calculates and prints their sum.
THANK YOU

More Related Content

PPTX
Licão 12 decision loops - statement iteration
PDF
PPTX
Case, Loop & Command line args un Unix
PDF
Osp2.pdf
PDF
Operating_System_Lab_ClassOperating_System_2.pdf
PPT
PHP CONDITIONAL STATEMENTS AND LOOPING.ppt
PPTX
Shell Programming Language in Operating System .pptx
PDF
Linux shell script-1
Licão 12 decision loops - statement iteration
Case, Loop & Command line args un Unix
Osp2.pdf
Operating_System_Lab_ClassOperating_System_2.pdf
PHP CONDITIONAL STATEMENTS AND LOOPING.ppt
Shell Programming Language in Operating System .pptx
Linux shell script-1

Similar to Unix Shell Programming subject shell scripting ppt (20)

PPT
34-shell-programming asda asda asd asd.ppt
PPTX
AOS_Module_3ssssssssssssssssssssssssssss.pptx
PPT
ShellProgramming and Script in operating system
PPT
34-shell-programming.ppt
PPTX
Web Application Development using PHP Chapter 2
PPT
Shell Scripting
PPTX
Linux System Administration
PDF
Loop and while Loop
PPTX
Scripting ppt
PPTX
Lecture 3
PPTX
Loops c++
PPTX
Linux Shell Scripting
PPT
Shell programming
PPTX
Licão 11 decision making - statement
DOCX
What is a shell script
PDF
PROBLEM SOLVING USING NOW PPSC- UNIT -2.pdf
PPTX
Loops in python.pptx/ introduction to loops in python
PPTX
introduction to loops in python/python loops
PPTX
Switch case and looping
34-shell-programming asda asda asd asd.ppt
AOS_Module_3ssssssssssssssssssssssssssss.pptx
ShellProgramming and Script in operating system
34-shell-programming.ppt
Web Application Development using PHP Chapter 2
Shell Scripting
Linux System Administration
Loop and while Loop
Scripting ppt
Lecture 3
Loops c++
Linux Shell Scripting
Shell programming
Licão 11 decision making - statement
What is a shell script
PROBLEM SOLVING USING NOW PPSC- UNIT -2.pdf
Loops in python.pptx/ introduction to loops in python
introduction to loops in python/python loops
Switch case and looping
Ad

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
cuic standard and advanced reporting.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Getting Started with Data Integration: FME Form 101
PDF
Encapsulation theory and applications.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
A Presentation on Artificial Intelligence
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
Spectroscopy.pptx food analysis technology
PDF
Encapsulation_ Review paper, used for researhc scholars
Per capita expenditure prediction using model stacking based on satellite ima...
SOPHOS-XG Firewall Administrator PPT.pptx
MYSQL Presentation for SQL database connectivity
cuic standard and advanced reporting.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Spectral efficient network and resource selection model in 5G networks
Getting Started with Data Integration: FME Form 101
Encapsulation theory and applications.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
A comparative analysis of optical character recognition models for extracting...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Reach Out and Touch Someone: Haptics and Empathic Computing
Programs and apps: productivity, graphics, security and other tools
A Presentation on Artificial Intelligence
Network Security Unit 5.pdf for BCA BBA.
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Spectroscopy.pptx food analysis technology
Encapsulation_ Review paper, used for researhc scholars
Ad

Unix Shell Programming subject shell scripting ppt

  • 1. UNIT 5 Branching Control Structures, Loop-Control Structure, and Continue and break Statements, Expressions, Command Substitution, Command Line Arguments and Functions.
  • 2. Branching Control Structures • Branching control structures allow you to control the flow of execution based on certain conditions. The main branching control structures in shell scripting are: • if-else statements: These statements evaluate a condition and execute one block of code if the condition is true, and another block of code if the condition is false. • case statements: Also known as switch statements in other programming languages, case statements provide multiple conditional branches based on the value of a variable.
  • 3. Examples #!/bin/bash # Example script to check if a number is even or odd echo "Enter a number:" read number if [ $((number % 2)) -eq 0 ]; then echo "$number is even." else echo "$number is odd." fi OUTPUT: Enter a number: 7 7 is odd.
  • 4. Examples #!/bin/bash # Example script to determine the day of the week based on a number echo "Enter a number (1-7):" read day case $day in 1) echo "Monday" ;; 2) echo "Tuesday" ;; 3) echo "Wednesday" ;; 4) echo "Thursday" ;; 5) echo "Friday" ;; 6) echo "Saturday" ;; 7) echo "Sunday" ;; *) echo "Invalid input. Please enter a number between 1 and 7." ;; esac OUTPUT: Enter a number (1-7): 3 Wednesday
  • 5. Loop-Control Structure • Loop-control structures allow you to execute a block of code repeatedly until a certain condition is met. The main loop-control structures in shell scripting are: • for loops: These loops iterate over a sequence of values or elements. • while loops: These loops execute a block of code repeatedly as long as a specified condition is true. • until loops: These loops execute a block of code repeatedly until a specified condition becomes true.
  • 6. FOR • A for loop construct can be used to execute a set of statements repeatedly as long as a given condition is true. • Here, expr1 contains initialization statement expr2 contains limit test expression expr3 contains updating expression • Firstly, expr1 is evaluated. It is executed only once. • Then, expr2 is evaluated to true or false. • If expr2 is evaluated to false, the control comes out of the loop w/o executing the body of the loop. • If expr2 is evaluated to true, the body of the loop (i.e. statement1) is executed. • After executing the body of the loop, expr3 is evaluated. • Then expr2 is again evaluated to true or false. This cycle continues until expression becomes false. Syntax: for(expr1;expr2;expr3) { statement1; }
  • 7. EXAMPLE #!/bin/sh for i in 1 2 3 4 5 do echo “welcome $i times” done OUTPUT
  • 8. Iterate over all files in the current directory #!/bin/bash # Iterate over all files in the current directory for file in *; do echo "Processing file: $file" done OUTPUT: Processing file: file1.txt Processing file: file2.txt Processing file: directory
  • 9. Nested loop #!/bin/bash # Nested loop example for (( i=1; i<=3; i++ )); do echo "Outer loop iteration: $i" for (( j=1; j<=2; j++ )); do echo "Inner loop iteration: $j" done done OUTPUT: Outer loop iteration: 1 Inner loop iteration: 1 Inner loop iteration: 2 Outer loop iteration: 2 Inner loop iteration: 1 Inner loop iteration: 2 Outer loop iteration: 3 Inner loop iteration: 1 Inner loop iteration: 2
  • 10. WHILE SYNTAX: while (expression) { statement1 } • A while loop construct can be used to execute a set of statements repeatedly as long as a given condition is true. • Firstly, the expression is evaluated to true or false. • If expression is evaluated to false, the control comes out of the loop w/o executing the body of loop. • If the expression is evaluated to true, the body of the loop is executed. • After executing the body of the loop, the expression is again evaluated to true or false. This cycle continues until expression becomes false.
  • 11. EXAMPLE } OUTPUT #!/bin/sh a=0 while [$a –lt 10] do echo “$a” a=$(($a+1)) done
  • 12. #!/bin/bash # Prompt the user to enter a number echo "Enter a number (0 to exit):" # Initialize the variable to store user input number=1 # Execute the loop until the user enters 0 while [ $number -ne 0 ]; do read -r number echo "You entered: $number" done • echo "Exiting the loop " OUTPUT: Enter a number (0 to exit): 5 You entered: 5 10 You entered: 10 0 You entered: 0 Exiting the loop. Reading user input until a specific condition is met
  • 13. #!/bin/bash # Prompt the user to enter the length of the Fibonacci sequence echo "Enter the length of the Fibonacci sequence:“ # Read the user input read -r length # Initialize variables for Fibonacci sequence a=0 b=1 count=1 Generating a Fibonacci sequence
  • 14. # Execute the loop to generate the Fibonacci sequence echo "Fibonacci sequence:“ while [ $count -le $length ]; do echo -n "$a " fn=$((a + b)) a=$b b=$fn ((count++)) Done echo "" # Print a newline after the sequence OUTPUT: Enter the length of the Fibonacci sequence: 8 Fibonacci sequence: 0 1 1 2 3 5 8 13
  • 15. Until Loop • In an "until" loop, the loop continues executing the code block until the specified condition evaluates to true. • It is essentially the opposite of a "while" loop. • Syntax: until [ condition ]; do # Code to be executed as long as the condition is false done
  • 16. UNTIL LOOP #!/bin/bash counter=0 until [ $counter -eq 5 ]; do echo "Counter: $counter" ((counter++)) done echo "Loop finished." OUTPUT: Counter: 0 Counter: 1 Counter: 2 Counter: 3 Counter: 4 Loop finished.
  • 17. Squares using Until Loop #!/bin/bash target=10 current=1 until [ $current -ge $target ]; do echo "Current Value: $current" ((current *= 2)) done echo "Loop finished." OUTPUT: Current Value: 1 Current Value: 2 Current Value: 4 Current Value: 8 Loop finished.
  • 18. Continue and break Statements • These statements are used within loops to control the flow of execution. • continue: This statement causes the loop to skip the rest of the current iteration and move to the next iteration. • break: This statement causes the loop to terminate immediately, regardless of the loop's condition.
  • 19. CONTINUE STATEMENTS • The continue statement is similar to the break command, except that it causes the current iteration of the loop to exit, rather than the entire loop. • This statement is useful when an error has occurred but you want to try to execute the next iteration of the loop. • Syntax: continue [n] //if n is mentioned then it continues from the nth enclosing loop.
  • 20. Example #!/bin/sh for i in $(seq 1 5) do if (($i==3)) then continue fi echo $i done OUTPUT: 1 2 4 5
  • 21. Print even numbers between 1 and 10, skipping odd numbers #!/bin/bash echo "Even numbers between 1 and 10:“ for ((i = 1; i <= 10; i++)); do # Check if the number is odd if [ $((i % 2)) -ne 0 ]; then # Skip to the next iteration if the number is odd continue fi # Print the even number echo "$i" OUTPUT: Even numbers between 1 and 10: 2 4 6 8 10
  • 22. BREAK STATEMENT • The break statement is used to terminate the execution of the entire loop, after completing the execution of all of the lines of code up to the break statement. • It then steps down to the code following the end of the loop. • Syntax: break [n] // n is number of nested loops . // By default the value of n is 1.
  • 23. Example #!/bin/sh for i in $(seq 1 10) do if (($i==5)) then break fi echo $i done OUTPUT: 1 2 3 4
  • 24. Find the first negative number in a list of numbers #!/bin/bash echo "Finding the first negative number in the list:" numbers=(5 10 -3 8 -6 2 4) for num in "${numbers[@]}"; do # Check if the number is negative if [ $num -lt 0 ]; then # Print the first negative number and exit the loop echo "The first negative number is: $num" break fi done OUTPUT: Finding the first negative number in the list: The first negative number is: -3
  • 25. Expressions • Expressions in shell scripting are combinations of operators, variables, and values that evaluate to a single value. • They are commonly used in conditions and assignments.
  • 26. Arithmetic Expressions #!/bin/bash result=$((10 + 5 * 2)) echo "Result of arithmetic expression: $result" OUTPUT: Result of arithmetic expression: 20
  • 28. Comparison Expressions #!/bin/bash value1=10 value2=20 if [ $value1 -eq $value2 ]; then echo "Values are equal" else echo "Values are not equal" fi OUTPUT: Values are not equal
  • 29. Logical Expressions #!/bin/bash age=25 if [ $age -ge 18 ] && [ $age -lt 60 ]; then echo "You are an adult" else echo "You are not an adult" fi OUTPUT: You are an adult
  • 30. Command Substitution • Command substitution allows you to use the output of a command as part of another command or expression. • It can be done using backticks (`) or the $() syntax.
  • 31. Basic Command Substitution #!/bin/bash current_date=$(date) echo "Current date and time: $current_date" OUTPUT: Current date and time: <current_date_and_time>
  • 32. Using Command Output in a Loop #!/bin/bash echo "Files in the current directory:" for file in $(ls); do echo "$file" done OUTPUT: Files in the current directory: file1.txt file2.txt directory
  • 33. Command Substitution with Pipe #!/bin/bash # Command substitution with pipe example cpu_info=$(cat /proc/cpuinfo | grep "model name" | uniq) echo "CPU information: $cpu_info" OUTPUT: CPU information: model name : Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
  • 34. Command Substitution in Arithmetic Expression #!/bin/bash total_files=$(ls | wc -l) echo "Total number of files in the current directory: $total_files" OUTPUT: Total number of files in the current directory: <number_of_files>
  • 35. Command Line Arguments • Command line arguments are values provided to a script or program when it is executed from the command line. • They can be accessed within the script using special variables like $1, $2, etc., which represent the first, second, and subsequent arguments passed to the script.
  • 36. Basic Command Line Argument #!/bin/bash echo "First argument: $1" OUTPUT: ./script.sh hello First argument: hello
  • 37. Multiple Command Line Arguments #!/bin/bash echo "First argument: $1" echo "Second argument: $2" echo "Third argument: $3" OUTPUT: ./script.sh hello world 123 First argument: hello Second argument: world Third argument: 123
  • 38. Using Command Line Arguments in a Loop #!/bin/bash echo "Command line arguments:“ for arg in "$@"; do echo "$arg" done OUTPUT: ./script.sh one two three Command line arguments: one two three
  • 39. Arithmetic Operation with Command Line Arguments #!/bin/bash result=$(( $1 + $2 )) echo "Sum of $1 and $2 is: $result" OUTPUT: ./script.sh 5 10 Sum of 5 and 10 is: 15
  • 40. Functions • Functions in shell scripting allow you to encapsulate blocks of code for reuse. • They are defined using the function keyword or by simply declaring them with their names followed by parentheses. • Functions can take arguments and return values.
  • 41. Basic Function #!/bin/bash greet() { echo "Hello, World!" } # Call the function greet OUTPUT: Hello, World!
  • 42. Function with Parameters #!/bin/bash greet() { echo "Hello, $1!" } # Call the function with an argument greet "John" OUTPUT: Hello, John!
  • 43. Function with Return Value #!/bin/bash add() { result=$(( $1 + $2 )) echo $result } # Call the function and store the result in a variable sum=$(add 5 10) echo "Sum: $sum" OUTPUT: Sum: 15
  • 44. Function with Local Variables #!/bin/bash calculate() { local a=5 local b=10 local result=$(( a * b )) echo "Result inside function: $result" } # Call the function calculate OUTPUT: Result inside function: 50
  • 45. Function Calling Another Function #!/bin/bash say_hello() { echo "Hello!" } say_goodbye() { echo "Goodbye!" } greet() { say_hello say_goodbye } • # Call the parent function OUTPUT: Hello! Goodbye!
  • 46. Recursive Function #!/bin/bash factorial() { if [ $1 -eq 1 ]; then echo 1 else local prev=$(factorial $(( $1 - 1 ))) echo $(( $1 * prev )) fi } # Calculate factorial of 5 result=$(factorial 5) echo "Factorial of 5 is: $result" OUTPUT: Factorial of 5 is: 120
  • 47. Function with Default Parameter #!/bin/bash greet() { name=${1:-"World"} echo "Hello, $name!" } # Call the function with and without argument greet greet "John" OUTPUT: Hello, World! Hello, John!
  • 48. Function Returning Multiple Values #!/bin/bash get_system_info() { os=$(uname -s) kernel=$(uname -r) echo "$os $kernel" } # Call the function and store the result in variables info=$(get_system_info) echo "System information: $info" OUTPUT: System information: Linux 5.4.0-91-generic
  • 49. Function with Error Handling #!/bin/bash divide() { if [ $2 -eq 0 ]; then echo "Error: Division by zero" exit 1 fi result=$(( $1 / $2 )) echo "Result: $result" } # Call the function with different arguments divide 10 2 divide 10 0 OUTPUT: Result: 5 Error: Division by zero
  • 50. Practice Programs • Write a shell script that uses a for loop to print the multiplication table of a given number. • Create a script that iterates over a list of cities and prints a welcome message for each city. • Create a script that prompts the user for three numbers and prints their average using a for loop. • Write a shell script that displays the calendar for each month of a given year using a for loop. • Create a script that generates a random password of a specified length using a for loop. • Write a shell script that calculates the sum of digits of a given number using a while loop. • Create a script that reads numbers from the user until a negative number is entered, then calculates and prints their sum.