Operating System - HP-UX
1833378 Members
3286 Online
110052 Solutions
New Discussion

Re: strange error in shell script

 
Igor Ushkalo
New Member

strange error in shell script

We got strange shell behavior in one script. Tested on Linux/AIX/Unixware - everything Ok, only HP-UX failes (script hangs forever).
We pass output of some command ("ls" of directory, which contains 1000 files or "cat" etc.) to "while read ..." loop. Inside the loop we run some commands in background and wait for completion of these commands, but "wait" lasts forever (because "ls" command acts as a "job" and "wait" command waits for it.
System: rp8400, HP-UX 11.11, sh/ksh
Testcase:
##################
i=0
while true
do
echo $i > newfile${i}.txt
i=`expr $i + 1`
if [ $i -eq 1000 ]; then
break
fi
done
echo "Done create files..."
FILES_LIST=fileslist.lst
if [ -f $FILES_LIST ]; then
rm -f $FILES_LIST
fi
echo "Total files count "`ls -1 | wc -l`
ls -1 | while read FILENAME
do
jobs
echo $FILENAME >> $FILES_LIST &
jobs
echo $FILENAME
wait
done
##################
Has anybody an explanation? We have workaround, but we'd like to understand the cause of this trouble!
3 REPLIES 3
Peter Godron
Honored Contributor

Re: strange error in shell script

Igor,
could it be that not the ls but the | acts as a job?
If you shorten for ls loop to:
ls -1 *.txt | while read FILENAME
do
jobs
wait
done
You will see that a job[1] is running, which I believe could be the pipe.
Regards
Jdamian
Respected Contributor

Re: strange error in shell script

I agree with Peter.

Read the following paragraph extracted from ksh manual pages:

A pipeline is a sequence of one or more commands separated by |. The standard output of each command except the last is connected by a pipe (see pipe(2)) to the standard input of the next command. Each command is run as a separate process; the shell waits for the last command to terminate. The exit status of a pipeline is the exit status of the last command in the pipeline.
Igor Ushkalo
New Member

Re: strange error in shell script

Thanks, people!
We should use () to avoid such situation, for example instead of
ls -1|while read f;do jobs;echo $f;done
we should use
ls -1|(while read f;do jobs;echo $f;done)