Help on bash script?

Ian Smith smithi at nimnet.asn.au
Fri Aug 12 19:18:27 GMT 2005


On Fri 12 Aug 2005 09:33:54 +0800 Xu Qiang <Qiang.Xu at fujixerox.com> wrote:

 > 		find / -type f -name core -print | while read COREFILE ; do
 > 			NCOREFILES=$[ $NCOREFILES + 1 ] # a bit strange - xq
 > 			echo $NCOREFILES # xq
 > 
 > 			NEWNAME="${HOSTNAME}esscore${NCOREFILES}_${TIMESTAMP}"
 > 			# record mapping so people can go back and figure out
 > 			# where they came from
 > 			echo -e $NEWNAME "    was    " `ls -l $COREFILE` >> $SAVE_DIR/$CORELOG
 > 			mv $COREFILE $SAVE_DIR/$NEWNAME
 > 
 > 			echo "There are $NCOREFILES core files." # xq
 > 		done
 > 
 > 	fi
 > 
 > 	# What confused me most is the value $NCOREFILES outside 
 > 	# the do-while loop (but still in this function) reverted 
 > 	# back to its initial value, which seems contradictory to 
 > 	# our concept of local variables. - xq
 > 	#echo $NCOREFILES 

It's been pointed out that the find piped to while runs in a subshell,
and that changes to variables within aren't seen by its parent, but one
way around this is to avoid using a pipe, thus a subshell, for instance:

    find / -type f -name "*.core" -print >tempfile
    while read COREFILE; do
        [.. stuff ..]
        NCOREFILES=$(($NCOREFILES + 1))
    done <tempfile
    echo $NCOREFILES

I use sh, not bash, but suspect that this should work in bash too.

cheers, Ian



More information about the freebsd-questions mailing list