---
# System prepended metadata

title: L5. Bash Scripting. Part 2

---

# L5. Bash Scripting. Part 2

## For
for var in list
do
commands
done
```bash=
#!/bin/bash

for var in first second third fourth fifth; do
	echo The $var item
done
```

```bash=
#!/bin/bash
for file in /home/likegeeks/*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
fi
done
```

```bash=
#!/bin/bash
my_file="/etc/passwd"
for var in $(cat $my_file); do
	echo " $var"
done
```

#### Field separators
* Space
* Tab
* newline
```bash=
IFS=$'\n'
IFS=:
```
```bash=
#!/bin/bash
file="/etc/passwd"
IFS=$'\n'
for var in $(cat $file); do
	echo " $var"
done
```

#### Nested loops
```bash=
#!/bin/bash
IFS=$'\n'
for entry in $(cat /etc/passwd)
do
echo "Values in $entry –"
IFS=:
for value in $entry
do
echo " $value"
done
done
```

---

## While
while condition; do
commands
done

```bash=
#!/bin/bash
number=10
while [ $number -gt 4 ]; do
	echo $number
	number=$(($number - 1))
done
```
---

## Operators
* break
* continue

#### break
```bash=
#!/bin/bash
for var1 in 1 2 3 4 5 6 7 8 9 10
do
if [ $var1 -eq 5 ]
then
break
fi
echo "Number: $var1"
done
```

```bash=
#!/bin/bash
var1=1
while [ $var1 -lt 10 ]
do
if [ $var1 -eq 5 ]
then
break
fi
echo "Iteration: $var1"
var1=$(( $var1 + 1 ))
done
```

#### continue
```bash=
#!/bin/bash
for (( var1 = 1; var1 < 15; var1++ ))
do
if [ $var1 -gt 5 ] && [ $var1 -lt 10 ]
then
continue
fi
echo "Iteration number: $var1"
done 
```

---

## Redirecting the loop output
```bash=
#!/bin/bash
for (( a = 1; a < 10; a++ ))
do
echo "Number is $a"
done > myfile.txt
echo "finished."
```