Linux shell script – for loop using ranges or counting

Linux shell script – for loop using ranges or counting

The for loop can be set using the numerical range. The range is specified by a beginning and ending number. The for loop executes a sequence of commands for each member in a list of items. A representative example in BASH is as follows to display multiplication table with for loop (multiplication.sh):

#!/bin/bash
n=$1
# make sure command line arguments are passed to the script
if [ $# -eq 0 ]
then
	echo "A shell script to print multiplication table."
	echo "Usage : $0 number"
	exit 1
fi

# Use for loop
for i in {1..10}
do
	echo "$n * $i = $(( $i * $n))"
done

Save and close the file. Run it as follows:

chmod +x multiplication.sh
./multiplication.sh 
./multiplication.sh 13

Sample outputs:

13 * 1 = 13
13 * 2 = 26
13 * 3 = 39
13 * 4 = 52
13 * 5 = 65
13 * 6 = 78
13 * 7 = 91
13 * 8 = 104
13 * 9 = 117
13 * 10 = 130

For any query or issue, feel free to discuss on http://discuss.eduguru.in