Tips and Tricks About Computers, Web Development, Linux, the Internet and the Like
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)
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;
| Print article | This entry was posted by Tyler Mulligan on February 3, 2010 at 8:02 pm, and is filed under Bash, Linux, Programming, Ubuntu, Uncategorized. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |

about 5 months ago
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.
about 5 months ago
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