Bash - Sequence

> Procedural Languages > Bash Shell and (Unix|Linux) Utilities (XCU)

1 - About

A sequence expression is a construct that creates sequence of numbers or characters.

Advertising

3 - Syntax

It's a brace expansion and takes the form

{x..y}

where x and y are either:

A correctly-formed brace expansion must contain:

  • unquoted opening
  • closing braces,
  • and at least one unquoted comma or a valid sequence expression.

Any incorrectly formed brace expansion is left unchanged.

A { or , may be quoted with a backslash to prevent its being considered part of a brace expression.

To avoid conflicts with parameter expansion, the string ${ is not considered eligible for brace expansion.

4 - Management

4.1 - Creation

4.1.1 - Integers

When integers are supplied, the expression expands to each number between x and y, inclusive.

echo {1..10}
1 2 3 4 5 6 7 8 9 10
Advertising

4.1.2 - Character

When characters are supplied, the expression expands to each character lexicographically between x and y, inclusive. Note that both x and y must be of the same type.

echo {a..f}
a b c d e f

4.2 - Loop

4.2.1 - Integer For

Bash - For Statement

  • With hard-coded limit
for i in {1..10}; 
do 
    echo $i; 
done 
# or
for (( n=1; n<=10; n++ ))  
do  
    echo "$n"
done  
  • With variable limit
end=10
for i in $(seq 1 $end); 
do 
    echo $i; 
done

4.2.2 - Integer While

Bash - While

count=0  
while [ $count -le 10 ]  
do  
    echo "$count"
    count=$(( $count + 1 ))
done  
Advertising

4.2.3 - Character For

for letter in {a..f}  
do  
    echo "$letter"
done 
  • A array
for color in Blue Red
do  
    echo "$color"
done