# BASH -Conditions and Loops

### Working with Arrays <a href="#working-with-arrays" id="working-with-arrays"></a>

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[]}`*–*&#x72;eturns 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 `depts`array 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 <a href="#if-and-else-conditions" id="if-and-else-conditions"></a>

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.

```bash
#!/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.

```bash
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 <a href="#looping-structure-for" id="looping-structure-for"></a>

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.

```bash
#!/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.

```bash
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 <a href="#more-examples-for-loop" id="more-examples-for-loop"></a>

```bash
#!/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"
```

```bash
#!/bin/bash
echo "Starting FOR loop"
for files in $PWD/*.sh
do
echo "Printing File names:" $files
done
echo "Finished FOR loop"
```

```bash
#!/bin/bash
echo "Printing FOR loop"
for x in {1..5}
do
echo "Printing $x times"
done
echo "Finished FOR loop"
```

```bash
#!/bin/bash
echo "Starting FOR loop"
for j in {0..10..3}
do
echo "Printing $j value"
done
echo "Finished FOR loop"
```

```bash
#!/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"
```

```bash
#!/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 <a href="#looping-structure-while" id="looping-structure-while"></a>

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.

```bash
#!/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 <a href="#break-and-continue-inside-loop" id="break-and-continue-inside-loop"></a>

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.

```bash
 #!/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
```

```bash
#!/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 <a href="#case-statements" id="case-statements"></a>

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.

```bash
#!/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
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sai11101989.gitbook.io/devops/terminal-programming/bash-conditions-and-loops.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
