boyang
boyang

Reputation: 717

Busybox ash bug - cannot concat strings in while loop?

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?

Upvotes: 0

Views: 2905

Answers (1)

Brad
Brad

Reputation: 3530

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

Upvotes: 1

Related Questions