shell脚本中数组函数的问题
我正在尝试制作一个小的shell脚本功能,从根本上讲,它应该只返回我的两个最新版本的github存储库(不计算最新版本)。 这是我的代码:
get_release() {
curl --silent \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/user/repo/releases |
grep '"tag_name":' |
sed -E 's/.*"([^"]+)".*/\1/'
}
#str="1.1.1 2.2.2 3.3.3 4.4.4 5.5.5 6.6.6 7.7.7 8.8.8 9.9.9"
str=($get_release)
#VERSION=$(get_release)
IFS=', ' read -r -a array <<< "$str"
LASTVERSION=${array[-2]}
PENULTIMATEVERSION=${array[-3]}
echo "${LASTVERSION}"
echo "${PENULTIMATEVERSION}"
但是当我尝试运行时,我会得到这个:
t.sh: line 17: array: bad array subscript
t.sh: line 18: array: bad array subscript
注意:注释的str变量只是对数组正常工作的模拟,但是当尝试使用get_release函数时,我会遇到此错误。
I am trying to make a small shell script function where basically it should return me only the two latest versions of a github repository (not counting the latest).
Here is my code:
get_release() {
curl --silent \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/user/repo/releases |
grep '"tag_name":' |
sed -E 's/.*"([^"]+)".*/\1/'
}
#str="1.1.1 2.2.2 3.3.3 4.4.4 5.5.5 6.6.6 7.7.7 8.8.8 9.9.9"
str=($get_release)
#VERSION=$(get_release)
IFS=', ' read -r -a array <<< "$str"
LASTVERSION=${array[-2]}
PENULTIMATEVERSION=${array[-3]}
echo "${LASTVERSION}"
echo "${PENULTIMATEVERSION}"
But I'm getting this when I try to run:
t.sh: line 17: array: bad array subscript
t.sh: line 18: array: bad array subscript
Note: the commented str variable is just a simulation of an array, with it working normally, but when trying to use the get_release function, I get this error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为一个工作示例,与3.2向前的所有bash释放兼容:
...截至现在的日期正确发射(对于
juji-io/datalevin
上述示例中使用的项目):As a working example which is compatible with all bash releases from 3.2 forward:
...which as of present date correctly emits (for the
juji-io/datalevin
project used in the example above):根据 @Philippe 的评论
($get_release)
不会调用您的函数,但$(get_release)
会。根据 @Charles Duffy 和 @glenn jackman 的评论,我已经更新了代码片段,以安全地检查和访问数组的最后一个元素。
这是修改后的代码片段:
这是另一个基于 perl、正则表达式和捕获组的解决方案,即
As per @Philippe's comments
($get_release)
will not call your function, but$(get_release)
will.As per @Charles Duffy and @glenn jackman's comments for I've updated the code snippet for safely checking and accessing the last elements of an array.
Here's the amended code snippet:
Here's another solution based on perl, regex, and capture groups, i.e.
感谢所有帮助我的人,我能够通过以下方式解决这个问题:
Thanks to everyone who helped me, I was able to solve it this way: