Skip to content

Instantly share code, notes, and snippets.

@skipcloud
Last active July 13, 2020 10:09
Show Gist options
  • Save skipcloud/5dec1a6b36cc7093cc9048bea686785b to your computer and use it in GitHub Desktop.
Save skipcloud/5dec1a6b36cc7093cc9048bea686785b to your computer and use it in GitHub Desktop.
A shell function to fetch and display the Word of the Day

I wrote a shell function to fetch the Word of the Day from Wordnik.com.

You need to have jq installed as well as a Wordnik developer API key.

I've added it to my .bashrc file so I get the word of the day every time I start a new shell. To save making a request to the API each time a shell is opened I've saved the word of the day in a dotfile in the users home directory. If the dotfile is a day old then it will make a request and update the file.

If the -f option is provided it will fetch the word of the day anyway and update the dotfile.

# wod() returns the Word of the Day from Wordnik. 
# If an "-f" option is provided then the word of the day is fetched again.
wod() {
  if [ -z "$WORDNIK_API_KEY" ]; then
    echo "wod: Wordnik API key not set" >&2
    return 1
  fi

  if ! hash jq 2> /dev/null; then
    echo "wod: jq not installed" >&2
    return 1
  fi

  # store wod in a dot file so we only need to request it once a day
  file_path=$HOME/.wod

  # if the dot file exists and we don't want to fetch again
  if [ -f $file_path ] && [ "$1" != "-f" ]; then
    # check if the mod date is today
    date_fmt="+%Y-%m-%d"
    if [ "$(date -r $file_path $date_fmt)" = "$(date $date_fmt)" ]; then
      cat $file_path
      return 0
    fi
  fi

  # let's just assume the request works
  resp=$(curl -s "https://api.wordnik.com/v4/words.json/wordOfTheDay?api_key=$WORDNIK_API_KEY")

  word=$(jq '.word' <<< "$resp")
  kind=$(jq '.definitions[0].partOfSpeech' <<< "$resp" | sed 's/"//g')
  def=$(jq '.definitions[0].text' <<< "$resp" | sed 's/"//g')
  note=$(jq '.note' <<< $resp | sed 's/"//g')

  cat <<-END | fmt | tee $file_path
Word of the day: $word - $kind

Definition: $def

$note
END
}
@skipcloud
Copy link
Author

word of the day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment