坏阵列下标错误
问题描述:
我试图调试我的脚本,我是新的bash,我不明白错误 我想尝试多次改变它,我标记为60行 错误: 错误:./scriptdemo.txt:线60:results_array:坏数组下标坏阵列下标错误
#!/bin/bash
echo the script is running
#this part uses preCourses script to get preCourse demends for the input
course
results_array=''
reqursion_counter=-2
result_courses_counter=0
function FindPreCourses {
let reqursion_counter++
i=0
grep $1 courses.list>file1
while read line; do
res=$(echo $line|grep $1)
arr_line[$i]=$res
let i++
done<file1
rm file1
j=0
while (($j<${#arr_line[*]}))
do
read -a array_of_words<<<${arr_line[$j]}
length_of_line=${#array_of_words[*]}
if [[ 10#"$1" -eq 10#"${array_of_words[0]}" ]]; then
temp_line=${array_of_words[*]}
fi
let j++
done
read -a line_of_course<<<$temp_line
k=0
len=${#line_of_course[*]}
mistake_chk=1
if (($mistake_chk==1)); then
while ([[ ${line_of_course[$len-$k-1]} = +([0-9]) ]])&&
(((10#${line_of_course[$len-$k-1]} > 10)))
do
results_array[$result_courses_counter]=${line_of_course[$len-$k-1]}
let result_courses_counter++
let k++
done
if (($reqursion_counter < $result_courses_counter-1)); then
FindPreCourses ${results_array[$reqursion_counter]}
fi
fi
}
FindPreCourses $1
final=($(printf "%s\n" "${results_array[@]}" | sort -n))
printf '%s\n' "${final[@]}"|uniq
}
#this function searching for the sign students at the right semester
function looking_for_students {
grep $2 *.course>info2
local counter=0
while read line
do
grep $2 *.course | read -a line | echo ${line[0]}>fileName:ID
let counter++
done < info2
echo the number of the students counter was signing at $2 semester is
$counter
}
答
的主要问题是,您已定义results_array
作为一个正常的变量,但是使用它,就好像它是一个数组。在bash数组中有单独的声明语法。
使用此声明空数组:
results_array=()
或
declate -a results_array
尽管这样,也有一些完全不同的问题与您的代码,并作为@Cyrus建议,你应该有看看shellcheck来检查你的语法。
请看看:http://www.shellcheck.net/ – Cyrus
'results_array'不是数组,它是一个字符串:'results_array =''' – Barmar
A [mcve]隔离导致原因的最短代码同样的问题会对这个问题产生很大的影响。 –