shell 中嵌套for循环变量使用遇到的问题

使用嵌套for循环加break练习打印99乘法表时的代码

#!/usr/bin/bash


for i in {1..9}
do
        if [ $i -eq 1 ];then
                echo "1 * 1 = 1"
        else
        #       echo $i
                for j in  {1..$i}
                do
                        if [ $j -le $i ];then
                                echo -n "$i * $j  = $[$i*$j] "
                        else
                                break
                        fi
                done
                echo
        fi
done

当使用{}表示范围时会报以下错误

1 * 1 = 1
./chengfabiao.sh: line 12: [: {1..2}: integer expression expected

./chengfabiao.sh: line 12: [: {1..3}: integer expression expected

./chengfabiao.sh: line 12: [: {1..4}: integer expression expected

./chengfabiao.sh: line 12: [: {1..5}: integer expression expected

./chengfabiao.sh: line 12: [: {1..6}: integer expression expected

./chengfabiao.sh: line 12: [: {1..7}: integer expression expected

./chengfabiao.sh: line 12: [: {1..8}: integer expression expected

./chengfabiao.sh: line 12: [: {1..9}: integer expression expected``

使用序列seq可解决此问题

for i in {1..9}
do
        if [ $i -eq 1 ];then
                echo "1 * 1 = 1"
        else
        #       echo $i
                for j in  $(seq 1 $i)
                do
                        if [ $j -le $i ];then
                                echo -n "$i * $j  = $[$i*$j] "
                        else
                                break
                        fi
                done
                echo
        fi
done

你可能感兴趣的:(linux)