Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 13 Aug 2005 05:18:21 +1000 (EST)
From:      Ian Smith <smithi@nimnet.asn.au>
To:        freebsd-questions@freebsd.org
Cc:        Xu Qiang <Qiang.Xu@fujixerox.com>
Subject:   Help on bash script?
Message-ID:  <Pine.BSF.3.96.1050813044601.8009A-100000@gaia.nimnet.asn.au>
In-Reply-To: <20050812013604.8C12D16A422@hub.freebsd.org>

next in thread | previous in thread | raw e-mail | index | archive | help
On Fri 12 Aug 2005 09:33:54 +0800 Xu Qiang <Qiang.Xu@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




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?Pine.BSF.3.96.1050813044601.8009A-100000>