common inefficient shell code

Sun, 15 Aug 2010 11:28:14 +0200
rants

There is hardly any use in:

cat filename | while ...
do
...
done

Just do:

while ...
do
...
done < filename

If you want the while run in a subshell, use some parentheses, but you do not need the cat at all.

Another unnecessary inefficient idiom often seen is

foo="$(echo "$bar" | sed -e 's/|.*//')"

which can be replaced with the less forky

foo="${bar%%|*}"

Similarly there is

foo="${bar%|*}"

as short and fast variant of

foo="$(echo "$bar" | sed -e 's/|[^|]*$//')"

and the same with # instead of % for removing stuff from the beginning. (Note that both are POSIX, only the ${name/re/new} not discussed here is bash-specific).