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

标签 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[@]}

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

最佳答案

您没有正确地将值分配给 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/

相关文章:

python - 如果注释掉错误,Eclipse IDE(Pydev) 中内置 max() 函数和其他内置函数会出现错误

linux - Bluez 以编程方式删除单个设备的 BLE 绑定(bind)信息

linux - 为什么我会收到接近意外标记换行符的语法错误?

linux - Bash 脚本 : How to check if there's is only one root id?

linux - bash + linux机器中的进度对话框栏

python - 在 Windows bash 上 pip install flask 不起作用

python - if 语句不适用于抓取的网页文本

linux - 遍历数组,使用内容作为文件输出

在另一个文件中使用类引用的 Pythonic 方式

python - Python中如何判断一个多边形是否在另一个多边形内?