Skip to content

Instantly share code, notes, and snippets.

@ashsearle
Last active November 11, 2020 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashsearle/bb815eb99b429c0a8ec46a5bc45d16a4 to your computer and use it in GitHub Desktop.
Save ashsearle/bb815eb99b429c0a8ec46a5bc45d16a4 to your computer and use it in GitHub Desktop.
Shell script to display a random message once per day
#!/bin/bash
CONFIG_DIR=~/.config/motd
MESSAGES="${CONFIG_DIR}/messages"
MESSAGES_LAST_DISPLAY="${MESSAGES}-last-display"
if [ ! -f "$MESSAGES" ]; then
echo "$0: Store messages in '${MESSAGES}' (file does not exist)"
exit 1
fi
if [ ! -s "$MESSAGES" ]; then
echo "$0: Cannot find any messages in '${MESSAGES}'"
exit 1
fi
if [ ! -r "$MESSAGES" ]; then
echo "$0: Cannot read messages from '${MESSAGES}' (file is not readable)"
exit 1
fi
if [ -f "$MESSAGES_LAST_DISPLAY" ]; then
TODAY=$(date +%F)
LAST_DATE_DISPLAYED=$(date -r "$MESSAGES_LAST_DISPLAY" +%F)
if [ "$TODAY" == "$LAST_DATE_DISPLAYED" ]; then
# We already displayed a message today
# (One motivational message a day is enough)
exit 0
fi
fi
# Get a random message from the file:
MESSAGE=$(shuf -n 1 "$MESSAGES" 2> /dev/null)
if [ -z "$MESSAGE" ]; then
echo "$0: Empty message (blank line) found in '${MESSAGES}'"
exit 1
fi
# Using \033 instead of \e for escape codes as \e wasn't working in iTerm on macOS
echo -e "\033[38;5;81m${MESSAGE}\033[m"
# Create file or update its last-modified-time (mtime):
touch "$MESSAGES_LAST_DISPLAY" &> /dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment