Last Updated: February 25, 2016
· jkirchartz

Randomize Cowsay Critters

Cowsay is a fun little app that draws a cow that says things, but you can do so much more than a cow, there's all sorts of fun ascii art critters in there; but how do we get to them? Lots of solutions simply find the directory where cowfiles (the templates that define the critters) are stored and hard-code that; but how do you know where they are?

Turns out, cowsay will tell you if you pass the -l flag like so:

cowsay -l

which outputs the directory, and a list of all available cowfiles - much simpler than using find. But if there's a list of cowfiles there, why bother using ls to get the directory listing? simply trim off the first line by piping to sed, and ask it to delete it

cowsay -l  | sed "1 d"

now we've got a nice clean list to randomize; You could use shuf, or bash's built-in array-mangling utilities; for sake of portability, this script uses both:

#! /bin/bash
if type shuf > /dev/null; then
  cowfile="$(cowsay -l | sed "1 d" | tr ' ' '\n' | shuf -n 1)"
  cowfiles=( $(cowsay -l | sed "1 d") );
  cowfile=${cowfiles[$(($RANDOM % ${#cowfiles[*]}))]}
cowsay -f "$cowfile"

store that as a script (i.e. cowsay.sh), put it in your path, and soon you will find randomized cow bliss. check it out

fortune | cowsay.sh
Say Thanks
Filed Under