Random cow(ish) animals preaching quotes on Ubuntu 9.10

Looking for something interesting when I login to one of my servers, I decided to whip up the following script I appended to my ~/.bashrc file.

# fortune and cowsay are needed for the snippet to work, I had to install these first
sudo apt-get install fortune cowsay
COWDIR=/usr/share/cowsay/cows/; COWNUM=$(($RANDOM%$(ls $COWDIR | wc -l))); COWFILE=$(ls $COWDIR | sed -n ''$COWNUM'p'); fortune | cowsay -f $COWFILE

UPDATE:

Suggested by MrBougo, a shorter but perhaps more process intensive method:

fortune | cowsay -f $(ls /usr/share/cowsay/cows/ | shuf | head -n1)
random cowsay fortune

random cowsay fortune

Breaking down the script, the first 3 parts create variables and the last command executes the cowsay and quote.

# defines the directory of the cow files
COWDIR=/usr/share/cowsay/cows/;
 
# Get a random number limited to the number of files in the directory, making clever use of % (mod) and adding 1 to make sure it doesn't return 0
COWNUM=$(($RANDOM%$(ls $COWDIR | wc -l))+1);
 
# list the contents of the cow dir again, pipe to sed and use the number as a random line to get the name of a file
COWFILE=$(ls $COWDIR | sed -n ''$COWNUM'p');
 
# use fortune to get a quote, pipe to cowsay and use the file as defined above
fortune | cowsay -f $COWFILE;
Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • blogmarks
  • BlogMemes
  • Furl
  • NewsVine
  • Reddit
  • SphereIt
  • Spurl
  • StumbleUpon
  • Technorati
  • YahooMyWeb

2 comments so far

  1. Mr. Bougo February 4, 2010 1:41 pm

    Short one-liner: fortune | cowsay -f $(ls /usr/share/cowsay/cows/ | shuf | head -n1)

    It’s probably more expensive than picking one random line number, but we’re dealing with a relatively small list of files, so it’s not that much of a downside.

  2. zzxop February 16, 2010 3:01 am

    hi,i use the last method. but i get an error!

    bash: command substitution: line 14: syntax error near unexpected token `+1′
    bash: command substitution: line 14: `($RANDOM%$(ls $COWDIR | wc -l))+1′

    I use Xfce Terminal on archlinux

Leave a comment

Please be polite and on topic. Your e-mail will never be published.