One minute
Bash loops
The following scripts display the basic usage of the for
loop using bash.
The first assigns values directly –> ./ForLoop.sh
#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for i in 1 2 3 4 5
do
echo "i : $i"
done
Perhaps using a different format –> ./ForLoop.sh
#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for (( i=1; i<=5; i++ ))
do
echo "i : $i"
done
Assigning values as user entries –> ./ForLoop.sh 1 5
#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
varA=$1
varB=$2
for (( i="$varA"; i<="$varB"; i++ ))
do
echo "i : $i"
done
A classic nested loop –> ./ForLoop.sh
#!/bin/bash
# loop inside a loop
echo "Bash version ${BASH_VERSION}..."
varX=( one two three )
varY=( 10 20 26 39 48)
varZ=( "/A" "/B" "/C" )
for i in "${varX[@]}"
do
for j in "${varY[@]}"
do
for k in "${varZ[@]}"
do
echo $i $j $k
done
done
done
#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for day in Mon Tue Wed Thu Fri Sat Sun
do
echo -n "day $((i++ + 1)) : $day" # 1-5 are weekdays
if [ $i -eq 6 -o $i -eq 7 ]; then # 6-7 are weekend
echo " weekend"
continue;
fi
echo " weekday"
done
Read other posts