Introduction to Software Systems
  • About
  • Introduction
  • Software Engineering
    • Software System
    • Software Product Development
    • Computer Networks
  • Terminal Programming
    • BASH - Basic Commands
    • BASH - Conditions and Loops
    • Worked-out Examples
    • Practice Questions
  • Databases
    • Structured Databases
      • SQL Queries
      • Worked-out Example
    • Unstructured Databases
      • NoSQL Queries
      • Worked-out Example
  • Object Oriented Programming
    • Python - Introduction
    • Python - Basic Concepts
    • Python - Inbuilt Datastructures
    • Python - Conditions and Loops
    • Python - Lambda, Functions, Class/Objects
    • Worked-out Examples
  • WEB TECHNOLOGIES
    • HTML
    • CSS
    • Native JavaScript - Basics
    • Native JavaScript - Conditional Statements and Loops
    • Native JavaScript - Data Structures
    • JavaScript - Scope, Functions, Type Conversion
Powered by GitBook
On this page
  • Working with Arrays
  • If and Else Conditions
  • Looping Structure - for
  • More examples - For loop
  • Looping Structure - While
  • Break and Continue inside Loop
  • Case Statements
  1. Terminal Programming

BASH - Conditions and Loops

This page presents details about arrays, writing conditional statements and looing structures using BASH.

Working with Arrays

The Array is a type of variable which is the collection of multiple items of the same type. The counter in the array starts with zero –0. Declared as depts= (“cse” “cnd” “ece”) as depts being the name of the array. To fetch the output - echo $depts. Below are the variations on working with arrays.

  • echo $depts – will return 0th value or first value in the array i.e. cse

  • echo ${depts[]}–returns error as bad substitution

  • echo ${depts[2]} – returns third value i.e.

  • echo ${depts[3]} – returns nothing as there is no value for dept[3]

  • depts[3] = "research" – to insert the fourth element in the dept array

  • echo ${#depts[*]} – returns the count of elements in the array i.e. returns

  • echo ${depts[*]:2:1} – skips the first two elements and only prints the next one value i.e. returns

  • echo ${depts[]/research/phd} – replaces the “research” element in the array with “phd” on runtime. However, echo ${depts[]}still shows research as the change is only for runtime.

  • depts2 = echo ${depts[*]/research/phd}- to store the changed deptsarray into depts2 array. echo ${depts2[*]} returns values with phd in the fourth position.

  • echo sort <<<"${depts[*]}" - triple redirection to sort a text in array argument but not in a file argument.

If and Else Conditions

If and Else helps us handle and judge the conditions on data, we manage. Below are a few examples of Syntax. Highlighted are the required syntax constructs of if & else.

#!/bin/bash
if test $USER := "root" 
#to open if. Used $USER env variable to check user
then
{
clear
echo "Your are not root"
}
else
# to open else
{
clear
echo "Your are root"
}
fi#close the if 

Running If and Else on command like as below. As soon as you close if using fi keywords, the if and else logic will get executed directly.

root@ubuntu1:/scripts# numdays=400
root@ubuntu1:/scripts# echo $numdays
400
root@ubuntu1:/scripts# iftest "$numdays" -gt 100
>then
>{
>echo "Over Budget!"
>}
>fi
Over budget!
root@ubuntu1:/scripts#

Looping Structure - for

For loop is used to repeat a task in a specific number of times we would like to process something. Below for.sh is an example to demo a FOR loop with conduction using IN keyword to list of .sh files in each sub directory based on the total size of the file. The below script will print the size of all the .sh files in a list and then gives us the sum of the total size. Highlighted are the required syntax constructs for the For Loop.

#!/bin/bash
clear
#declaring variables so that can be used
totalsize=0
currentfilesize=0

#currentfile is a temporary variable used for counter
for currentfile in/scripts/*.sh 
do
        currentsize=`ls -l $currentfile | tr -s " " | cut -f5 -d " "`
    #Gets file size and cuts it with space delimiter
    #tr command to squeeze the space on the file name spaces
        let totalsize=$totalsize+$currentsize
    #calculate the totalsizeecho $currentsize
done
echo
echo "Total space used by Script files is:" $totalsize

Below is an example for FOR loop using an array.The Array is a variable contains multiple items of the same type. For example, cities=("Chennai", "Hyderabad") is an array with two items. echo $cities will print the first value in the cities array i.e. Chennai. Highlighted are the required syntax constructs for theFor Loop.@ value in the array to call each element based on the increment value of i.

echo ${cities[0]} #return Chennai
echo $(cities[1]} #will return "Hyderabad"
root@Ubuntu:/scripts# for((i=0;i<${#cities[@]};i++));do
>echo ${cities[$i]}
>done
ChennaiHyderabad

More examples - For loop

#!/bin/bash
echo "Starting FOR loop"
for val in 0 1 2 3 4 5
do
echo "Printing Value:" $val
done
echo " Finished FOR loop"
#!/bin/bash
echo "Starting FOR loop"
for files in $PWD/*.sh
do
echo "Printing File names:" $files
done
echo "Finished FOR loop"
#!/bin/bash
echo "Printing FOR loop"
for x in {1..5}
do
echo "Printing $x times"
done
echo "Finished FOR loop"
#!/bin/bash
echo "Starting FOR loop"
for j in {0..10..3}
do
echo "Printing $j value"
done
echo "Finished FOR loop"
#!/bin/bash
echo "Starting FOR loop"
for a in $(seq 1 4 20)
do
echo "Printing FOR value $a times"
done
echo "Finished FOR loop"
#!/bin/bash
echo "Starting FOR loop"
for ((i=1;i<10;i++))
do
echo "Printing $i entry in the loop"
done
echo "Finished FOR loop"

Looping Structure - While

Unlike a FOR loop, when we use WHILE loop –we don’t necessarily know how many times we are going through the loop. While.sh is an example script that prompts the user to select an option, so while the user doesn’t choose to exit and live in the loop. Highlighted are the required syntax constructs of WHILE Loop.

#!/bin/bash
choice="0"
while (( $choice != "1"))
do
    clear
    echo
    echo "Please select and Option" 
    echo
    echo "1 –Exit"
    echo
    read choice
done

The script waits for the input choice from the user. Until the input is given as1 the loop is not broken. The loop will execute initially as the choice value is zero by default and waits for the input, which will be in the loop unless the user gives the value as 1.

Break and Continue inside Loop

Depending on the code, we might wish to break out of the loop or continue the loop so that we go back to loop statements and run them again. Below is an example for a break and continue. Unless we type exit, we will not be able to break the loop, else it still continues to run the same while again and again.

 #!/bin/bash 
 while true
 do
 clear
 echo "To leave, Type exit" 
 echo 
 read -p "What did you say?" choice
 if test $choice = "exit"
 then
 {
 break
 }
 else
 {
 continue
 }
 done
#!/bin/bash
while true
do
echo "Welcome NEO - The Matrix has you"
echo "Choose wisely - Red Pill or Blue Pill?"
echo
read -p "What is your choice? - Type Red or Blue: " pill
if test $pill = "Blue"
then
{
break
}
else
{
echo "Welcome to Matrix. Thank you for choosing us"
continue
}
fi

Case Statements

Case statements help us to test the value of something for multiple possible items, instead of using a bunch of If-else, we can use Case statements. Below is an example case.sh for your reference. Highlighted are the constructs used in the case statements.

#!/bin/bash
clear
echo "City Type" 
echo 
read -p "Enter your City:" city 
case $city in "Hyderabad") city_type ="Tier 2";;
# Pipe Symbol is a OR command
"Bengaluru" |"Mumbai") city_type="Tier 1";;
"New Delhi") city_type= "Capital";;
# here star is to consider anything else
*)clear; echo "Invalid City $city";exit;;
esac
#case in reverse to close the case statement
clear
echo "City Typefor $city has been set to $city_type"
echo
PreviousBASH - Basic CommandsNextWorked-out Examples

Last updated 3 months ago