0

When programming with Busybox ash, str in following program will be changed in every while loop as expected, but after while loop the str becomes empty again. /tmp/term_mon_ttys is a test file.

#!/bin/ash
cnt=0
str=
cat /tmp/term_mon_ttys | while read line; do
    str="$str $cnt"
    cnt=`expr $cnt + 1`
done
echo $str

However, if changing above code to

#!/bin/ash
cnt=0
str=
while [ $cnt -lt 5 ]; do
    str="$str $cnt"
    cnt=`expr $cnt + 1`
done
echo $str

then after the while loop, the str becomes 0 1 2 3 4.

Anybody noticed this issue?

boyang
  • 617
  • 1
  • 7
  • 21

1 Answers1

1

Not an ash issue. The pipe creates a subshell so $str inside the while loop is not the same as the one outside.

This turns up regularly in shells. You can read more here: Bash Script: While-Loop Subshell Dilemma

Community
  • 1
  • 1
Brad
  • 2,785
  • 1
  • 18
  • 35