我是 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[@]}
但它不起作用。有人可以告诉我我做错了什么吗? 如果有人帮助我,我将不胜感激。
最佳答案
您没有正确地将值分配给 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) )
关于python - 如何将值附加到 bash shell 脚本中的空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41742197/