To display a random message, follow the following steps:
1: set up your ~/.bashrc file for customization by including a ~/.my-bashrc file, to the point you can display a static message through echo every time you open the terminal.
2: use something instead of echo to print a random message instead. There are two different methods we can use, depending on whether you want to display single-line messages or multi-line messages.
Random Single-Line Messages
Personally, I'd rather write 20 lines of Python than 5 lines of Bash, so usually I'd recommend just running a Python script from .my-bashrc to display a random line from a file. However, it turns out there is a simple way to do this with one line of Bash, so I guess no Python is needed this time.
The terminal command shuf can be used to open a file and print its lines in random order. In other words, it shuffles the lines of the file. Now we only need another command to print only the first line of the file and then we have a script that can print a random line from a .txt file for us. Conveniently, shuf can already do that thought its --head-count= or -n argument.
So to display a random message every time you open the terminal, all you need to do is have something like this in your .my-bashrc.
shuf --head-count=1 "~/Documents/Message of the day.txt"
And then you create a file called Message of the day.txt on your ~/Documents folder with one message per line and it will automatically display the random line for you.
Random Multi-Line Messages
If you want to display random multi-line messages, that unfortunately isn't possible with shuf, so we would have to use awk. But I don't want to do that because I wouldn't be able to understand what the code is doing 5 minutes after writing it, so let's just use Python for this instead.
1: create a Python script such as ~/.my-motd.py with the following code:
#!/bin/env python3
import random
import os.path
# Our entries will be separated by 3 slashes.
ENTRY_SEPARATOR = '---'
# Set the filepath for the messages
filepath = '~/Documents/Message of the day.txt'
# Expand the tilde to the full path
filepath = os.path.expanduser(filepath)
# Read the content from the file
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Pick a random entry
if content:
entries = content.split(ENTRY_SEPARATOR)
motd = random.choice(entries).strip()
else:
motd = None
# Displays the motd
if motd:
print(motd)
else:
# Customize this if you want
print("No message of the day today.")
2: make it executable.
3: run it from your ~/.my-bashrc.
# Displays my message of the day
~/.my-motd.py
4: create a ~/Documents/Messages of the day.txt where you put your multi-line messages separated by 3 slashes (---). Like this, for example:
Hello there, world.
--Signed, me.
---
Reminder: breathe.
Now, when whenever you open the terminal, Bash will source .bashrc, which sources .my-bashrc, which runs .my-motd.py.