linux – 语法错误:使用Bash时预期的操作数
发布时间:2020-12-13 23:07:08 所属栏目:Linux 来源:网络整理
导读:我有两个我想要循环的数组.我正确地构造它们,然后在进入for循环之前,我确实回应它们以确保数组的一切正常. 但是当我运行脚本时,它输出一个错误: l=: syntax error: operand expected (error token is "=" 我咨询了强大的谷歌,我明白它缺少第二个变量,但我之
我有两个我想要循环的数组.我正确地构造它们,然后在进入for循环之前,我确实回应它们以确保数组的一切正常.
但是当我运行脚本时,它输出一个错误: l<=: syntax error: operand expected (error token is "<=" 我咨询了强大的谷歌,我明白它缺少第二个变量,但我之前提到我确实回应了价值观,一切似乎都没问题.这是片段.. #!/bin/bash k=0 #this loop is just for being sure array is loaded while [[ $k -le ${#hitEnd[@]} ]] do echo "hitEnd is: ${hitEnd[k]} and hitStart is: ${hitStart[k]}" # here outputs the values correct k=$((k+1)) done k=0 for ((l=${hitStart[k]};l<=${hitEnd[k]};l++)) ; do //this is error line.. let array[l]++ k=$((k+1)) done for循环中的变量被正确回显,但循环不起作用..我在哪里错了? # 正如gniourf_gniourf回答:
意思是错误输出不显示在循环的开头,但是当k的值大于数组的索引时,指向该数组不包含的索引… 解决方法
那是因为在某些时候${hitEnd [k]}扩展为空(未定义).我得到((l< =))相同的错误.您应该将for循环写为:
k=0 for ((l=${hitStart[0]};k<${#hitEnd[@]} && l<=${hitEnd[k]};l++)); do 以便总是有一个索引k对应于数组${hitEnd [@]}中的已定义字段. 而且,而不是 k=$((k+1)) 你可以写 ((++k)) 完成! 使用更好的现代bash练习修改您的脚本: #!/bin/bash k=0 #this loop is just for being sure array is loaded while ((k<=${#hitEnd[@]})); do echo "hitEnd is: ${hitEnd[k]} and hitStart is: ${hitStart[k]}" # here outputs the values correct ((++k)) done k=0 for ((l=hitStart[0];k<${#hitEnd[@]} && l<=hitEnd[k];++l)); do ((++array[l])) ((++k)) done 现在,我不太确定for循环是否完全符合你的要求……难道你的意思不是这样吗? #!/bin/bash # define arrays hitStart[@] and hitEnd[@]... # define array array[@] #this loop is just for being sure array is loaded for ((k=0;k<${#hitEnd[@]};++k)); do echo "hitEnd is: ${hitEnd[k]} and hitStart is: ${hitStart[k]}" # here outputs the values correct ((++k)) done for ((k=0;k<${#hitEnd[@]};++k)); do for ((l=hitStart[k];l<=hitEnd[k];++l)); do ((++array[l])) done done (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |