4.3 Creating variables from STDOUT

BASH offers an easy way to store the results of a command in a variable. Simple encompass a command within parenthesis and put a $ in front.

seq 1 10
numbers=$(seq 1 10)
echo $numbers
1
2
3
4
5
6
7
8
9
10
1 2 3 4 5 6 7 8 9 10

Here we introduced the handy command seq that creates a sequence of numbers. If only two arguments are given, seq interprets these are the first and last numbers of a sequence. The call seq 1 10 used above, for instance, creates the sequence 1, 2, …, 10. But seq can also be used to create more complex sequences by providing three arguments: the first number, the increment and the last number of the sequence.

seq 0 3 12
seq 1 3 12
0
3
6
9
12
1
4
7
10

By default, seqseparates the numbers by a space or new line. We can change the separator to any string use the option -s.

seq -s+ 1 10
1+2+3+4+5+6+7+8+9+10

We will make use of seq a lot to create dummy examples, such as this one:

result=$(seq -s* 1 10 | bc)
echo $result
3628800

Here, we first created a sequence of numbers from 1 through 10 separated by a “*“, which we then passed to bc, the BASH calculator. The result was finally stored in a variable result.