Skip to content

Instantly share code, notes, and snippets.

@ashsearle

ashsearle/motd

Last active Nov 11, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.