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
Osp2.pdf
PPTX
AOS_Module_3ssssssssssssssssssssssssssss.pptx
PDF
PPTX
Scripting ppt
PPTX
Case, Loop & Command line args un Unix
PPTX
Shell Programming Language in Operating System .pptx
PDF
Operating_System_Lab_ClassOperating_System_2.pdf
Licão 12 decision loops - statement iteration
Osp2.pdf
AOS_Module_3ssssssssssssssssssssssssssss.pptx
Scripting ppt
Case, Loop & Command line args un Unix
Shell Programming Language in Operating System .pptx
Operating_System_Lab_ClassOperating_System_2.pdf

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

DOCX
What is a shell script
PPS
UNIX - Class3 - Programming Constructs
PPTX
Scripting ppt
PPTX
Unix shell scripts
PPT
ShellProgramming and Script in operating system
PPT
ShellAdvanced shell scripting programm.ppt
PPT
Bash Programming
PPT
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
PPTX
Repetition Structures
PPTX
Bash and regular expressions
DOCX
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
DOCX
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
PPT
Chap06
PPTX
Scripting 101
PPT
34-shell-programming asda asda asd asd.ppt
PDF
Module 03 Programming on Linux
PDF
Shell Scripting Intermediate - RHCSA+.pdf
PPTX
Licão 11 decision making - statement
PPT
Shell programming
What is a shell script
UNIX - Class3 - Programming Constructs
Scripting ppt
Unix shell scripts
ShellProgramming and Script in operating system
ShellAdvanced shell scripting programm.ppt
Bash Programming
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
Repetition Structures
Bash and regular expressions
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
of 70UNIX Unbounded 5th EditionAmir Afzal .docx
Chap06
Scripting 101
34-shell-programming asda asda asd asd.ppt
Module 03 Programming on Linux
Shell Scripting Intermediate - RHCSA+.pdf
Licão 11 decision making - statement
Shell programming
Ad

Recently uploaded (20)

PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Encapsulation theory and applications.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Cloud computing and distributed systems.
PDF
Approach and Philosophy of On baking technology
PDF
Empathic Computing: Creating Shared Understanding
PDF
Electronic commerce courselecture one. Pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
MIND Revenue Release Quarter 2 2025 Press Release
Mobile App Security Testing_ A Comprehensive Guide.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Spectral efficient network and resource selection model in 5G networks
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Network Security Unit 5.pdf for BCA BBA.
Encapsulation theory and applications.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Review of recent advances in non-invasive hemoglobin estimation
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Cloud computing and distributed systems.
Approach and Philosophy of On baking technology
Empathic Computing: Creating Shared Understanding
Electronic commerce courselecture one. Pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Advanced methodologies resolving dimensionality complications for autism neur...
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.