Eine variable verändert sich innerhalb einer while-Schleife wird nicht gespeichert

In dem folgenden Programm, wenn ich die variable $foo auf den Wert 1 innerhalb der ersten if Aussage, es funktioniert in dem Sinne, dass Ihr Wert wird gespeichert nach der if-Anweisung. Allerdings, wenn ich die gleiche variable auf den Wert 2 innerhalb einer if die in einem while Aussage, es ist vergessen, nach der while Schleife. Es verhält sich so wie ich über irgendeine Art von Kopie der variable $foo innerhalb der while loop und ich bin nur das veränderte, insbesondere kopieren. Hier ist eine komplette test-Programm:

#!/bin/bash

set -e
set -u 
foo=0
bar="hello"  
if [[ "$bar" == "hello" ]]
then
    foo=1
    echo "Setting \$foo to 1: $foo"
fi

echo "Variable \$foo after if statement: $foo"   
lines="first line\nsecond line\nthird line" 
echo -e $lines | while read line
do
    if [[ "$line" == "second line" ]]
    then
    foo=2
    echo "Variable \$foo updated to $foo inside if inside while loop"
    fi
    echo "Value of \$foo in while loop body: $foo"
done

echo "Variable \$foo after while loop: $foo"

# Output:
# $ ./testbash.sh
# Setting $foo to 1: 1
# Variable $foo after if statement: 1
# Value of $foo in while loop body: 1
# Variable $foo updated to 2 inside if inside while loop
# Value of $foo in while loop body: 2
# Value of $foo in while loop body: 2
# Variable $foo after while loop: 1

# bash --version
# GNU bash, version 4.1.10(4)-release (i686-pc-cygwin)
Schlüssel Lesen Sie hier: ich Variablen in einer Schleife, die in einer pipeline. Warum verschwinden Sie, nachdem die Schleife beendet wird? Oder, warum kann ich nicht weiterleiten von Daten zu Lesen?.
Die shellcheck utility fängt diese (siehe github.com/koalaman/shellcheck/wiki/SC2030); Ausschneiden und einfügen der oben genannten code in shellcheck.net Probleme in diesem feedback für Zeile 19: SC2030: Modification of foo is local (to subshell caused by pipeline).

InformationsquelleAutor Eric Lilja | 2013-05-31

Schreibe einen Kommentar