简体   繁体   中英

How can I append values to an empty array in bash shell script?

I am a beginner in bash script programming. I wrote a small script in Python to calculate the values of a list from an initial value up to the last value increasing with 0.5. The Python script is:

# A script for grid corner calculation. 
#The goal of the script is to  figure out the longitude values which increase with 0.5

# The first and the last longitude values according to CDO sinfo
L1 = -179.85
L2 = 179.979
# The list of the longitude values
n = []             

while (L1 < L2):
    L1 = L1 + 0.5
    n.append(L1)

print "The longitude values are:", n 
print "The number of longitude values:", len(n)

I would like to create a same script by bash shell. I tried the following:

!#/bin/bash
L1=-180
L2=180
field=()

while [ $L1 -lt $L2 ]
do
  scale=2
  L1=$L1+0.5 | bc
  field+=("$L1")

done

echo ${#field[@]}

but it does not work. Could someone inform me what I did wrong? I would appreciate if someone helped me.

You aren't correctly assigning the value to L1 . Also, -lt expects integers, so the comparison will fail after the first iteration.

while [ "$(echo "$L1 < $L2" | bc)" = 1 ]; do
do
  L1=$(echo "scale=2; $L1+0.5" | bc)
  field+=("$L1") 
done

If you have seq available, you can use that instead, eg,

field=( $(seq -f %.2f -180 0.5 179.5) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM