for bash中的循环退出到早期没有错误

时间:2016-10-21 21:22:11

标签: bash

为什么我的for循环:for((i = 1; i< = $ n,i ++))工作?我无法弄清楚这一点。当n是例如4时,行echo $n返回4,但它不会再次进入循环。我也没有收到任何错误。我试着制作一个小循环,如:

for ((i=1, i<=$n; i++)); do 
    echo "this works" 
done

这很好用,这对我来说更奇怪:/。提前致谢

read n
length=16
p=()
p[1]=50
rest=63
function s() {
    arr=($@)
    line="_____________________________________________________________________"
    for i in ${arr[@]}; do
        line=$( echo $line |  sed s/./1/$i)
    done
    echo $line
}
for ((i=1; i<=$n; i++)); do
    echo $n
    for ((j=1; j<=$length; j++)); do
        s ${p[@]}
    done
    len=${#p[@]}
    ((len=$len*2))
    for ((k=1; k<=$len; k+=2)); do
        ((p[$k+1]=p[$k]+1))
        ((p[$k]=p[$k]-1))
    done
    for ((l=1; l<=$length; l++)); do
        s ${p[@]}
        len=${#p[@]}
        for ((m=1; m<=$len; m+=2)); do
            ((p[$m+1]=p[$m+1]+1))
            ((p[$m]=p[$m]-1))
        done
    done
    ((rest=$rest-2*$length))
    ((length=$length/2))
done

1 个答案:

答案 0 :(得分:0)

如果你没有声明你的变量是局部的,那么它们是全局的 - 所以s函数中的循环会覆盖函数外部使用的相同i计数器,导致外循环提前退出。

考虑使用以下代码:

s() {
    local -a arr  # declare a function-local array (sparse, like all bash arrays)
    local i       # ...and a function-local counter

    for i; do     # by default, a for statement iterates over "$@"; that works for us.
      arr[$i]=1   # specifically set a value only for named items
    done

    # ...thereafter, iterate through the range of characters we want to print...
    for ((i=0; i<70; i++)); do
      printf '%s' "${arr[$i]:-_}" # and print the array entry if present, or an _ otherwise
    done
    printf '\n'                   # ...followed by a trailing newline.
}