Merikanto

一簫一劍平生意,負盡狂名十五年

Bash Programming - 03 Flow Control

This post is Part Three of Bash Programming. Today let’s look at flow control.



Conditions

if

Format:

1
2
3
4
5
6
7
if [[ ... ]]; then
...
elif [[ ... ]]; then
...
else
...
fi

e.g. Input number & 7:

1
2
3
4
5
6
7
8
9
read -p "Input: " a

if [[ $a > 7 ]]; then
echo Bigger
elif [[ $a = 7 ]]; then
echo Equal
else
echo Smaller
fi

case

Format:

1
2
3
4
5
6
case <VAR> in 
..1) # Can be digits or strings.
... ;;
..2)
... ;;
esac

e.g. Month & Half-year:

1
2
3
4
5
6
7
8
9
10
read -p "Input: " a

case $a in
1 | 2 | 3 | 4 | 5 | 6)
echo "1st half of the year";;
7 | 8 | 9 | 10 | 11 | 12)
echo "2nd half of the year";;
*)
echo "Input error";;
esac


Loops

for

Bash-Type:

1
2
3
4
5
6
sum=0

for n in {1..5}; do
let "sum += n"
done
echo "Total is: $sum"

C-Type:

1
2
3
4
5
6
sum=0

for (( n = 1; n <=5; n++ )); do
let "sum += n"
done
echo "Total is: $sum"

while

e.g. Calculate sum of 1 - 10:

1
2
3
4
5
6
7
s=0
n=1
while (( $n <= 10 )); do // while n ≤ 10
let "s += n"
let "n++"
done
echo "Total is: $s"

until

e.g. Calculate sum of 1 - 10:

1
2
3
4
5
6
7
s=0
n=1
until (( $n > 10 )); do // until n > 10
let "s += n"
let "n++"
done
echo "Total is: $s"

select

e.g. Select words

1
2
3
4
5
6
7
8
9
10
PS3="Select: "
select w in hello world; do
echo -e "Result: \n $w"
done

>>> 1) hello
>>> 2) world
>>> Select: 1
>>> Result:
>>> hello

Note that echo -e: Recognize \, escape.

PS3 is the prompt. Default is #?.


Nested Loop

1
2
3
4
5
6
7
8
n=3
while [[ $n > 0 ]]; do
echo "Outer $n"
let "n--"
for (( i=2; i>0; i-- )); do
echo "Inner $i"
done
done

break

Out of all loops

1
2
3
4
5
6
7
8
9
10
11
12
n=0
while [[ $n <= 4 ]]; do
echo $n
if [[ $n == 2 ]]; then
break // break AFTER echo
fi
let n++
done

>>> 0
1
2

Note: break after echo


continue

Out of current loop

1
2
3
4
5
6
7
8
9
10
11
for n in {0..4}; do
if [[ $n == 2 ]]; then
continue // continue BEFORE echo
fi
echo $n
done

>>> 0
1
3
4

Note: continue before echo