Lem is right on this!
If I change to KSH, my a.sh works fine.
$cat a.sh
$! /bin/ksh
zipfile=$1
pattern=$2
i=0
unzip -qq -l ${zipfile} | grep ${pattern} | while read a b c d
do
i=$((i+1))
X[$i]="${d}"
echo "$i) ${X[$i]}"
done
echo "X[*]= \"${X[*]}\""
printf "%s\n" "${X[*]}"
echo "--"
printf "%s\n" "${X[@]}"
$./a.sh test.zip a
$ ./a.sh test.zip a
1) a
2) aa
3) aaa
X[*]= "a aa aaa"
a aa aaa
--
a
aa
aaa
For the pipeline, it is difference between bash and ksh
in ksh manual:
"Each command, except possibly the last, is run as a separate process;
while in bash manual:
"Each command in a pipeline is executed as a separate process (i.e., in a subshell)." as Lem pasted.
So my a.sh works find in ksh because the while doesn't run in subshell.
Then I add ps -e f in my script to approve this:
$ cat a.sh
#! /bin/ksh
zipfile=$1
pattern=$2
i=0
unzip -qq -l ${zipfile} | grep ${pattern} | while read a b c d
do
ps -e f
sleep 3
i=$((i+1))
X[$i]="${d}"
echo "$i) ${X[$i]}"
done
echo "X[*]= \"${X[*]}\""
printf "%s\n" "${X[*]}"
echo "--"
printf "%s\n" "${X[@]}"
$ ./a.sh test.zip a
4308 pts/2 Ss 0:00 \_ bash
7230 pts/2 S+ 0:00 | \_ /bin/ksh ./a.sh test.zip a
7235 pts/2 R+ 0:00 | \_ ps -e f
If I changed ksh to bash, I got:
4308 pts/2 Ss 0:00 \_ bash
7261 pts/2 S+ 0:00 | \_ /bin/bash ./a.sh test.zip a
7264 pts/2 S+ 0:00 | \_ /bin/bash ./a.sh test.zip a
7265 pts/2 R+ 0:00 | \_ ps -e f
Thanks everyone for the reply.
hehe2046
--
http://compgroups.net/comp.unix.shell/array-lost-its-values/1949314