Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array with a sequence of numbers in bash

Tags:

arrays

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} 

Until now I was using a 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 with constant intervals).

Is there a way to create such an array in a single command? what is the most efficient way to create such a list?

like image 678
jarhead Avatar asked Sep 01 '16 09:09

jarhead


People also ask

How do I create a sequence of numbers in bash?

You can iterate the sequence of numbers in bash in two ways. One is by using the seq command, and another is by specifying the range in for loop. In the seq command, the sequence starts from one, the number increments by one in each step, and print each number in each line up to the upper limit by default.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is use of the read command in shell?

The read command reads one line from standard input and assigns the values of each field in the input line to a shell variable using the characters in the IFS (Internal Field Separator) variable as separators.


1 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)) 

You can then 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 have commas instead of dots for decimals. This can be changed setting LC_NUMERIC="en_US.UTF-8".

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

$ echo {0..15..3} 0 3 6 9 12 15 
like image 91
fedorqui 'SO stop harming' Avatar answered Oct 22 '22 18:10

fedorqui 'SO stop harming'