A bash for loop is a bash programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script. For example, you can run UNIX command or task 5 times or read and process list of files using a for loop.
A loop is a powerful programming tool that enables you to execute a set of commands repeatedly. In this chapter, we will examine the following types of loops available to shell programmers − The while loop. The for loop. The until loop.
$0 is the name of the script itself (script.sh) $1 is the first argument (filename1) $2 is the second argument (dir1)
Brace expansion, {x..y} is performed before other expansions, so you cannot use that for variable length sequences.
Instead, use the seq 2 $max
method as user mob stated.
So, for your example it would be:
max=10
for i in `seq 2 $max`
do
echo "$i"
done
Try the arithmetic-expression version of for
:
max=10
for (( i=2; i <= $max; ++i ))
do
echo "$i"
done
This is available in most versions of bash, and should be Bourne shell (sh) compatible also.
Step the loop manually:
i=0 max=10 while [ $i -lt $max ] do echo "output: $i" true $(( i++ )) done
If you don’t have to be totally POSIX, you can use the arithmetic for loop:
max=10 for (( i=0; i < max; i++ )); do echo "output: $i"; done
Or use jot(1) on BSD systems:
for i in $( jot 0 10 ); do echo "output: $i"; done
If the seq
command available on your system:
for i in `seq 2 $max`
do
echo "output: $i"
done
If not, then use poor man's seq
with perl
:
seq=`perl -e "\$,=' ';print 2..$max"`
for i in $seq
do
echo "output: $i"
done
Watch those quote marks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With