这是我运行时遇到的错误:
./sortNums.sh: line 10: [: 4: unary operator expected
./sortNums.sh: line 10: [: 4: unary operator expected
./sortNums.sh: line 10: [: 4: unary operator expected
./sortNums.sh: line 10: [: 4: unary operator expected
./sortNums.sh: line 10: [: 4: unary operator expected
./sortNums.sh: line 10: [: 4: unary operator expected
./sortNums.sh: line 10: [: 4: unary operator expected
./sortNums.sh: line 10: [: 4: unary operator expected
./sortNums.sh: line 10: [: -gt: unary operator expected
./sortNums.sh: line 10: [: -gt: unary operator expected
./sortNums.sh: line 10: [: -gt: unary operator expected
./sortNums.sh: line 10: [: -gt: unary operator expected
./sortNums.sh: line 10: [: -gt: unary operator expected
./sortNums.sh: line 10: [: -gt: unary operator expected
./sortNums.sh: line 10: [: -gt: unary operator expected
./sortNums.sh: line 10: [: -gt: unary operator expected
脚本:
#!/bin/bash
bubbleSort()
{
for ((i=0;i<=${#nums[@]};i++))
do
for ((j=0;j<=${#nums[@]};j++))
do
if [ ${nums[$i]} -gt ${nums[$j]} ]
then
t=${nums[$i]}
nums[$i]=${nums[$j]}
nums[$j]=$t
fi
done
done
}
declare -a nums=(89 62 11 75 8 33 95 4)
echo ${nums[*]} #prints out all elems
bubbleSort
echo ${nums[*]} #prints out all elems
答案1
您正在执行i <= ${#nums[@]}
。正如您所知,bash 中的数组是从 0 开始索引的,因此最后一个元素位于${#nums[@]} - 1
。当i
并且${#nums[@]}
您执行nums[$i]=${nums[$j]}
或 时nums[$j]=$t
,您会在数组末尾添加,从而增加数组的大小,从而创建无限循环。
您看到的错误也是由于这个原因,但由于分配尚未完成,因此${array[non-existent index]}
只是空的。考虑下面的输出bash -x
:
+ (( j++ )) # j is 8
+ (( j<=8 )) # perfectly fine
+ '[' 4 -gt ']' # but nums[j] is empty
./foo.sh: line 9: [: 4: unary operator expected
+ (( j++ ))
+ (( j<=8 ))
+ (( i++ ))
+ (( i<=8 ))
+ (( j=0 ))
+ (( j<=8 ))
+ '[' 89 -gt 4 ']'
+ t=89
+ nums[$i]=4
+ nums[$j]=89
+ (( j++ ))
+ (( j<=8 ))
+ '[' 4 -gt 4 ']'
+ (( j++ ))
+ (( j<=8 ))
+ '[' 4 -gt 62 ']'
+ (( j++ ))
+ (( j<=8 ))
+ '[' 4 -gt 75 ']'
+ (( j++ ))
+ (( j<=8 ))
一直这样下去,直到表达式为[ -gt ]
。如果只有一个参数,测试只是针对非空参数,因此会成功,然后进行赋值,然后开始无限循环。
做:
- 始终引用你的变量。
不:
- 在具有 0 索引数组的语言中测试数组末尾测试是否相等。