To loop through a numeric sequence on bash, use the following syntax
for i in {1..5}
do
echo "Loop: $i"
done
# Expected output:
Loop: 1
Loop: 2
Loop: 3
Loop: 4
Loop: 5
To increment more than 1:
# Only works in Bash version 4.0+
# To check your Bash version: echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
do
echo "Loop: $i"
done
# Expected output:
Loop: 0
Loop: 2
Loop: 4
Loop: 6
Loop: 8
Loop: 10
To decrement, just reverse the order of starting and ending numbers:
# Loop from 5 to 1 ...
for i in {5..1}
do
echo "Loop: $i"
done
# Loop from 10 to 0, decrementing by 2 each time ...
for i in {10..0..2}
do
echo "Loop: $i"
done
One-liner version of the for loop:
for i in {1..5}; do echo "Loop: $i"; done
# Expected output:
Loop: 1
Loop: 2
Loop: 3
Loop: 4
Loop: 5
# To execute more than one command per iteration
for i in {1..5}; do echo "Loop: $i"; echo "This too"; done
# Expected output:
Loop: 1
This too
Loop: 2
This too
Loop: 3
This too
Loop: 4
This too
Loop: 5
This too
Hey There, I am Amey Anekar - Cyber Security Specialist with a passion for solving security problems even when resources are limited. I've been fortunate to develop a knack for gauging an organization's cyber security posture and helping them plan a transition towards becoming more resilient in the face of cyber threats. It's a privilege to be able to contribute to the field and assist organizations in safeguarding their digital assets.