Site icon DesignLinux

Bash Sequence Expression (Range)

Bash while Loop

Using Bash sequence expression you can generates a range of integers or characters by providing the start and the end point of the range. In this guide, we will show you the basics of the sequence expression in Bash.

Bash Sequence Expression

Below is the basic form of the sequence expression:

{START..END[..INCREMENT]}

The expression starts with an opening brace and ends with a closing brace.

Below is the expression in action:

echo {0..5}

If the INCREMENT is not provided the default increment is 1:

0 1 2 3 4 5

To print the alphabet use below:

echo {a..z}
a b c d e f g h i j k l m n o p q r s t u v w x y z

When the END value is greater than the START value then the expression will create a range in decrement:

for i in {5..0}
do
  echo "Number: $i"
done
Number: 5
Number: 4
Number: 3
Number: 2
Number: 1
Number: 0

If an INCREMENT is given, it is used as the step between each generated item. Let’s see an example with increment value:

for i in {0..25..5}
do
  echo "Number: $i"
done
Number: 0
Number: 5
Number: 10
Number: 15
Number: 20
Number: 25

When using integers to generate a range, you can add a leading 0 to force each number to have the same length. To pad generated integers with leading zeros prefix either START and END with a zero:

for i in {00..3}
do
  echo "Number: $i"
done
Number: 00
Number: 01
Number: 02
Number: 03

If you want the rang with any prefix or suffix, you can set prefix or suffix with other characters as following:

echo A{00..5}B
A00B A01B A02B A03B A04B A05B

If the expression is not correct, there will be no change:

echo {0..}
0..

Conclusion

You learned how to generate a range of integers or characters using the Bash sequence expression.

If you have any questions or feedback, feel free to leave a comment.

Exit mobile version