A variable modified inside a while loop is not remembered

后端 未结 8 2351
挽巷
挽巷 2020-11-21 05:06

In the following program, if I set the variable $foo to the value 1 inside the first if statement, it works in the sense that its value is remember

8条回答
  •  無奈伤痛
    2020-11-21 05:30

    UPDATED#2

    Explanation is in Blue Moons's answer.

    Alternative solutions:

    Eliminate echo

    while read line; do
    ...
    done <

    Add the echo inside the here-is-the-document

    while read line; do
    ...
    done <

    Run echo in background:

    coproc echo -e $lines
    while read -u ${COPROC[0]} line; do 
    ...
    done
    

    Redirect to a file handle explicitly (Mind the space in < <!):

    exec 3< <(echo -e  $lines)
    while read -u 3 line; do
    ...
    done
    

    Or just redirect to the stdin:

    while read line; do
    ...
    done < <(echo -e  $lines)
    

    And one for chepner (eliminating echo):

    arr=("first line" "second line" "third line");
    for((i=0;i<${#arr[*]};++i)) { line=${arr[i]}; 
    ...
    }
    

    Variable $lines can be converted to an array without starting a new sub-shell. The characters \ and n has to be converted to some character (e.g. a real new line character) and use the IFS (Internal Field Separator) variable to split the string into array elements. This can be done like:

    lines="first line\nsecond line\nthird line"
    echo "$lines"
    OIFS="$IFS"
    IFS=$'\n' arr=(${lines//\\n/$'\n'}) # Conversion
    IFS="$OIFS"
    echo "${arr[@]}", Length: ${#arr[*]}
    set|grep ^arr
    

    Result is

    first line\nsecond line\nthird line
    first line second line third line, Length: 3
    arr=([0]="first line" [1]="second line" [2]="third line")
    

提交回复
热议问题