小编Joz*_*cek的帖子

是 while 循环还是管道导致全局变量表现异常

请有人解释一下COUNTER以下代码中变量的奇怪行为(从我的观点来看)?

#!/bin/bash

COUNTER=0

function increment {
    ((COUNTER++))
}

function report {
    echo "COUNTER: $COUNTER ($1)"
}

function reset_counter {
    COUNTER=0
}

function increment_if_yes {
    answer=$1
    if [ "$answer" == "yes" ]
    then
        increment
    fi
}

function break_it {
    echo -e "maybe\nyes\nno" | \
    while read LL
    do
        increment_if_yes $LL
    done    
}

report start # counter should be 0
increment
report one
increment_if_yes yes
report two
increment_if_yes no
report "still two"

reset_counter
report reset

break_it
report "I'd expect one" …
Run Code Online (Sandbox Code Playgroud)

bash shell-script variable

5
推荐指数
2
解决办法
712
查看次数

标签 统计

bash ×1

shell-script ×1

variable ×1