Magic 8-ball written in bash

Have you ever wanted a magic 8ball to use at work? A real one, even though nice to have on your desk, is not always practical. When I had a real one on my desk people were forever playing with it when they came to talk to me.

Making one is very simple. All you need is an array of values to use as responses, and a way to pick one of them at random. I could have written this in any number of languages, but this one is written in bash for simplicity.

First you want to make sure that your bash profile has a local bin directory set up correctly. If you do not already have one, you should include the following in your .bashrc file.

export PATH=~/bin:$PATH

Create the ~/bin if it does not already exist, and within it create a new file called 8ball with the following contents:

   "Signs point to yes."
   "Reply hazy, try again."
   "Without a doubt."
   "My sources say no."
   "As I see it, yes."
   "You may rely on it."
   "Concentrate and ask again."
   "Outlook not so good."
   "It is decidedly so."
   "Better not tell you now."
   "Very doubtful."
   "Yes - definitely."
   "It is certain."
   "Cannot predict now."
   "Most likely."
   "Ask again later."
   "My reply is no."
   "Outlook good."
   "Don't count on it."
   "Very unlikely."
   "No - don't even think about it."
echo "${ANSWER[ $(( $RANDOM % ${#ANSWER[@]} )) ]}"

Once created you want to make sure it is executable, so use chmod to give it the correct permissions.

$ chmod +x ~/bin/8ball

At this point we can use the script just by using 8ball question e.g.

$ 8ball Will the unit tests pass today?
As I see it, yes.

Leave a Reply

Your email address will not be published. Required fields are marked *