[sclug] Bash script help
Alex Butcher
lug at assursys.co.uk
Sun Apr 26 09:48:48 UTC 2009
On Sun, 26 Apr 2009, Neil Haughton wrote:
> Thanks for your contributions. I have learned a hell of a lot. Fro example
> it has come as quite a surprise that unlike in other languages [ is not the
> start of an expression, but is a command in its own right, but now I know
> that my mistake makes perfect sense. The illumination on expansion (ie * )
> was also not quite what I expected, but that too I now understand.
>
> I suppose it reinforces the idea that a little knowledge is a dangerous
> thing, and that before attempting anything else I should read up on it a bit
> more beforehand! :-) RTFM, as they say.
We all continue to learn! To be honest, writing robust and efficient shell
scripts is something of an art; I continue to find subtle bugs (usually
related to handling filenames with spaces and other special characters!) and
performance improvements even now.
Only this week, I found that the idiom I use to loop through each line of a
file:
INPFILE="/etc/termcap"
NUMLINES=`wc -l ${INPFILE} | awk '{print $1}'`
let CURRLINE=$NUMLINES
while [ $CURRLINE -ge 1 ]; do
LINE=`tail -${CURRLINE} ${INPFILE} | head -1`
echo >/dev/null $LINE
let CURRLINE=$CURRLINE-1
done
can be hugely improved with
cat ${INPFILE} | while read LINE; do
echo >/dev/null $LINE
done
The latter is about 15 times faster.
> Thanks to you all.
> Neil.
Best Regards,
Alex.
More information about the Sclug
mailing list