Sending Messages to Users on a Server

Programmers are inherently idiosyncratic creatures, in my opinion. These idiosyncrasies manifest can spawn both innovation and stagnation in our coding practices. But I have recently been met with idiosyncrasies that have caused some Bad Coding HabitsTM in some of my teammates that none of my attempts to address have seemed to squash.

Some of my teammates have become accustomed to some bad git habits. They leave tons of uncommitted and unstashed changes on shared repos and don't clean up old branches. These kinds of behaviors can manifest in any team. We all develop Bad Coding HabitsTM. I know I have several I should do more to break.

Becoming frustrated with my team's growing problem with git etiquette, I decided to create a cron job to send a gentle reminder to my teammates to do some housekeeping. I created a bash script to send a randomized wall message on Tuesdays and Thursdays to anyone logged into our demo server. This may seem like using dynamite to catch a fish, but part of me really just wanted to figure out how to do something like this.

You Get a Message! And You Get a Message! And You Get a Message!

I knew a few things going in to this:
1. I need to send a message to all users logged into our demo server.
2. I wanted the message to not say it was specifically from me because I felt it'd be ignored.
3. I wanted to be able to send a randomized message from a list of messages.

Knowing this, I knew I had to write a cronjob (a scheduled action on a server) that executed a wall message. With this knowledge, all I had left to do was write out my messages and do a little digging into how to get a random integer in bash.

Let's take a look at the script and then go in some greater detail:

#!/bin/bash
# This script displays a message
# about good git etiquette to the user.

array=("Commit your changes early and often and before sending to QA."  
    "Good Housekeeping: Prune old branches. We got the commits!" 
    "A new branch does not mean lost work." 
    "Don't leave uncommitted or untashed changes on a repo.")

n=$((RANDOM%3+0))

echo "${array[n]}" | sudo /usr/bin/wall -n  

The script is fairly simple. It takes an array of four different messages, then determines a random integer between 0 & 3. Then it echoes out whatever message is at the random number index of the array and passes that the wall command.

A few key notes:

  • When using a lot of builtin commands in a shell script, it's important to give the full path of the command (i.e., /usr/bin/wall), rather than just the command. In general, it's just better to use full paths in scripts.
  • The wall command can only be sent "anonymously" as root. The -n flag indicates "no banner," so only the message itself without any other information is broadcast.

I set up a cronjob that runs as root on Tuesdays and Thursdays and executes gitreminder.sh and voila! Everyone gets a message!