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

时间:2017-01-19 12:49:44

标签: python linux bash shell

我是bash脚本编程的初学者。我在Python中编写了一个小脚本来计算列表的值,从初始值到最后一个值增加0.5。 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)

我想用bash shell创建一个相同的脚本。我尝试了以下方法:

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

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

done

echo ${#field[@]}

但它不起作用。有人可以告诉我我做错了什么吗? 如果有人帮助过我,我将不胜感激。

1 个答案:

答案 0 :(得分:2)

您没有正确地将值分配给L1。此外,-lt需要整数,因此在第一次迭代后比较将失败。

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

如果您有seq可用,则可以使用它,例如,

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