Variabler i whileslingor: Difference between revisions
Jump to navigation
Jump to search
Linuxwiki>Wikiadmin Skapade sidan med '== Variabler i whileslingor == Variabler i whileslingor exekveras i ett subshell och kommer inte att bevaras när whileslingan avslutas. Därför kan man använda en "here str...' |
m 3 revisions imported |
||
| (2 intermediate revisions by one other user not shown) | |||
| Line 12: | Line 12: | ||
while read line | while read line | ||
do | do | ||
if [[ "$line" == "second line" ]] | if <nowiki>[[ "$line" == "second line" ]]</nowiki> | ||
then | then | ||
foo=2 | foo=2 | ||
| Line 28: | Line 28: | ||
x behåller här sitt värde efter whileslingan, dvs i detta fall antalet filer/kataloger i /etc | x behåller här sitt värde efter whileslingan, dvs i detta fall antalet filer/kataloger i /etc | ||
[[Category:bash]] | |||
Latest revision as of 21:53, 11 May 2026
Variabler i whileslingor
Variabler i whileslingor exekveras i ett subshell och kommer inte att bevaras när whileslingan avslutas. Därför kan man använda en "here string" där bara en del exekveras i ett subshell.
Normalt ser en whileslinga ut t ex så här:
echo -e $lines | while read line ... done
Genom att flytta det initiala kommandot, "echo -e $lines" i detta fall, efter done och föregå det med <<< exekveras enbart "echo -e $lines" i ett subshell. Den färdiga koden ser då ut så här (variabeln $foo behåller nu sitt värde efter whileslingan):
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 -e "$lines")"
Ett annat exempel:
x=0 while read v do x=$(( $x + 1 )) done <<< "$(ls -d /etc)"
x behåller här sitt värde efter whileslingan, dvs i detta fall antalet filer/kataloger i /etc