h1

Shell tips 6: Efficiency

December 4, 2010

Avoid launching binary processes. This can make a huge difference to the efficiency of script.
The commands you can type in at the prompt take two quite different forms: actual programmes (also known as binaries) and “shell builtins”, which are subroutines with in the shell. The difference, by design, is not obvious.
Historically, external binary programmes have been replaced by builtins with the same syntax so that scripts will continue to work. Study of the man page for your chose shell or use of the “type” command will tell you which is which. Wherever possible, use
builtins instead.

Especially avoid the binary command “expr” which evaluates arithmetic expressions.

Sum=`expr 2 + 2`

use the builtin “let” instead

let Sum=2+2.

“expr” is particualrly dangerous because it is often written into loops. It takes thousands of clock cycles (and some disk access) to launch “expr”, and only a few clock cycles to perform the calculation.

Avoid unnecessary executable launches using pipelines.

cat $MyFile | while read Line
do
echo $Line | tr '[a-z]' ['A-Z']
#The executable tr is called once per
#line to put Line into upper case
done

can be much more efficiently written


cat $MyFile | tr '[a-z]' '[A-Z]'

In particular, invocation of the executables grep, awk and sed can be avoided by performing pattern matching with the builtin,”case”, (but only for some of the instances)

cat $MyFile | while read Name
do
if [ $(echo $Name | grep -c "^Mr" ]
then
echo male
fi
if [ $(echo $Name | grep -c "^Mrs" ]
then
echo female
fi
if [ $(echo $Name | grep -c "^Miss" ]
then
echo female
fi
if [ $(echo $Name | grep -c "^Ms" ]
then
echo female
fi
done


can be much more efficiently written

cat $MyFile | while read Name
do
case $Name in
"Mrs *")) echo female ;;
"Miss *")) echo female ;;
"Ms *")) echo female ;;
"Mr *")) echo male ;;
esac
done

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: