简体   繁体   English

如何在bash shell脚本中将值附加到空数组?

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

I am a beginner in bash script programming. 我是bash脚本编程的初学者。 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. 我用Python编写了一个小脚本来计算列表的值,该列表的值从初始值到最后一个值增加0.5。 The Python script is: Python脚本是:

# 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. 我想通过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 . 您没有将值正确分配给L1 Also, -lt expects integers, so the comparison will fail after the first iteration. 另外, -lt需要整数,因此比较将在第一次迭代后失败。

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, 如果您有可用的seq ,则可以改用它,例如,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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