Examples of for loops and if conditions in Bash

This week, we will see eleven examples of for loops and if conditions in Bash. All of them are commonly used in bioinformatics analyses.

For loops

Example 1

cells=( "neutrophils" "monocytes" "lymphocytes" "eosinophils" "basophils" )

for cell in ${cells[@]}; do
	echo ${cell}
done
neutrophils
monocytes
lymphocytes
eosinophils
basophils

Example 2

cells=( "neutrophils" "monocytes" "lymphocytes" "eosinophils" "basophils" )
n=$((${#cells[@]}-1))

for i in $(seq 0 $n); do
	echo ${cells[i]}
done
neutrophils
monocytes
lymphocytes
eosinophils
basophils

If conditions

Example 1 (string comparison with “or”)

cell="monocytes"

if [ "$cell" == 'neutrophils' ] || [ "$cell" == 'monocytes' ]; then
	echo the cell corresponds to neutrophils or monocytes

elif [ "$cell" == 'lymphocytes' ] || [ "$cell" == 'eosinophils' ]; then
	echo the cell corresponds to lymphocytes or eosinophils

else
	echo the cell does not correspond to any of these four cells
fi
the cell corresponds to neutrophils or monocytes

Example 2 (string comparison with “and”)

cell_i="monocytes"
cell_j="eosinophils"

if [ "$cell_i" == 'neutrophils' ] && [ "$cell_j" == 'monocytes' ]; then
	echo the cell corresponds to neutrophils or monocytes

elif [ "$cell_i" == 'lymphocytes' ] && [ "$cell_j" == 'eosinophils' ]; then
	echo the cell corresponds to lymphocytes or eosinophils

else
	echo the cells do not correspond to these possibilities
fi
the cells do not correspond to these possibilities

Example 3 (numerical comparison where ge means greater or equal)

i=4
j=4

if [ "$i" -ge "$j" ]; then
	echo i is greater or equal to j

else
	echo i is less than j
fi
i is greater or equal to j

Example 4 (numerical comparison where gt means greater than)

i=4
j=4

if [ "$i" -gt "$j" ]; then
	echo i is greater than j

else
	echo i is less or equal to j
fi
i is less or equal to j

Example 5 (numerical comparison where le means less or equal)

i=4
j=4

if [ "$i" -le "$j" ]; then
	echo i is less or equal to j

else
	echo i is greater than j
fi
i is less or equal to j

Example 6 (numerical comparison where lt means less than)

i=4
j=4

if [ "$i" -lt "$j" ]; then
	echo i is less than j

else
	echo i is greater or equal to j
fi
i is greater or equal to j

Example 7 (numerical comparison where eq means equal)

i=4
j=4

if [ "$i" -eq "$j" ]; then
	echo i is equal to j

else
	echo i is not equal to j
fi
i is equal to j

Example 8 (file existence test)

if [ -f "${file}" ]; then
	echo file exists
fi

Example 9 (directory existence test)

if [ -d "${directory}" ]; then
	echo directory exists
fi

Conclusion

In conclusion, we have seen today some examples of for loops and if conditions in Bash.

Related posts

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply