2-Cent Tips
2-cent Tip: Conditional pipes
Ben Okopnik [ben at linuxgazette.net]
Mon, 3 Aug 2009 22:43:05 -0500
In using Debian/Ubuntu, I often find myself doing an "apt-cache search <foo>" - i.e., searching the package database. Unfortunately, the copious return from the search often overruns my screen, requiring paging up - or, if I do remember to pipe the output to 'less', turns out to be annoyingly short (and now requires quitting out of the pager.) So, a little while ago, I decided to be lazy^Wefficient and write a script... actually, a function - a script wouldn't do, since the variable I'm looking for only exists in the current shell environment.
From my ~/.bashrc:
ac () { out=$(/usr/bin/apt-cache search "$@") if [ $(($(echo "$out"|/usr/bin/wc -l)+2)) -ge $LINES ] then echo "$out" | /usr/bin/less else echo "$out" fi } export -f ac
Using the $LINES Bash variable, which tells us how many lines our current terminal is capable of displaying, makes it relatively simple to decide whether to use a pipe or not. I also adjust the comparison a bit to account for the prompt.
-- * Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *
[ Thread continues here (10 messages/12.24kB) ]