Create an array with a sequence of numbers in bash

I would like to write a script that will create me an array with the following values:

{0.1 0.2 0.3 ... 2.5} 

So far I have used the script as follows:

 plist=(0.1 0.2 0.3 0.4) for i in ${plist[@]}; do echo "submit a simulation with this parameter:" echo "$i" done 

But now I need the list to be much longer (but still at regular intervals).

Is there any way to create such an array in one command? What is the most efficient way to create such a list?

+14
source share
3 answers

Using seq , you can say seq FIRST STEP LAST . In your case:

 seq 0 0.1 2.5 

Then it is a matter of storing these values ​​in an array:

 vals=($(seq 0 0.1 2.5)) 

Then you can check the values ​​with:

 $ printf "%s\n" "${vals[@]}" 0,0 0,1 0,2 ... 2,3 2,4 2,5 

Yes, my locale is set to comma instead of dots for decimals. This can be changed by setting LC_NUMERIC="en_US.UTF-8" .

By the way, brace expansion also allows you to set the increment. The problem is that it must be an integer:

 $ echo {0..15..3} 0 3 6 9 12 15 
+24
source

Bash supports C style. For loops:

 $ for ((i=1;i<5;i+=1)); do echo "0.${i}" ; done 0.1 0.2 0.3 0.4 
+3
source

Complementing the main answer

In my case, seq was not the best choice.
You can also use the jot utility to create a sequence. However, this command has more complex syntax.

 # 1 2 3 4 jot - 1 4 # 3 evenly distributed numbers between 0 and 10 # 0 5 10 jot 3 0 10 # abc ... z jot -c - 97 122 
0
source

All Articles