Tips & Tricks – TechKranti https://techkranti.com CyberSecurity Revolution Tue, 23 Jun 2020 08:40:49 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 169658937 Bash: Numeric For Loop https://techkranti.com/bash-numeric-for-loop/ Tue, 23 Jun 2020 08:40:26 +0000 http://techkranti.com/?p=183 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
]]>
183