Shell Script

Variable scope

Variable scope becomes important particularly when processing loops. Consider this example:

typeset -i counter=0
find ${backupPath} -name backup-archive-\*.bak.gz | while read backupFile
do
	echo "... removing $backupFile"
	let counter=counter+1
done
echo "Processed $counter files"

Loops execute inside a sub-shell.
While $counter will get incremented inside the loop it is a local (to the loop) variable and the last echo will not print a value.

The work-round I use is redirection, the above example rewritten:

typeset -i counter=0
while read backupFile
do
	echo "... removing $backupFile"
	let counter=counter+1
done < <( find ${backupPath} -name backup-archive-\*.bak.gz )
echo "Processed $counter files"

In this case the last echo will correctly show the number of files processed.

Note that the brackets and redirection operators should appear with exactly the spaces as shown.