A Handy Pushover Console Script

Stock photo of a smartphone, from https://www.pexels.com/photo/white-smartphone-1851415/

Pushover is a service that, after a one-time AppStore purchase, allows push notifications to be sent from within applications or via their API. I had used it for a while in conjunction with the Domoticz home automation tool to alert me of unexpected window opening events, but left my account dormant ever since. Recently faced with some Linux administration tasks that would require alerts when certain situations occurred, my memories of Pushover came back. So I created a wrapper that lets me use the service to either transfer textual messages alone, or even attach a graphics file. All that’s needed is curl to send the request, and optionally sed (for string sanitizing), as well as file and grep (to avoid sending non-image files as images).

The syntax is trivial: If the first argument is an image file, it will be transferred along with a string of the remaining command line. Otherwise, all arguments on the command line will be concatenated, length-limited (if necessary), and pushed to the device.



# Verify that at least one argument was passed
if [ $# -lt 1 ]; then
  echo "Usage: $0 [imagefile] <message string>"
  exit -1

# Check whether the first argument is an image file
if [ -f "$1" -a ! "$(file "$1" | grep -qE 'image|bitmap')" ]; then
  string="${*:2}" # Use remaining arguments as message
  if [ -z "$string" ]; then # Avoid empty message string
    string="See image attachment"
  string="$*" # Concatenate all arguments into message string

# Remove problematic characters from message string and limit length
string=$(echo $string | sed -e "s/\"/'/g" -e "s/=/-/g" | cut -c 1-1024)

# Create the Pushover request URL
cmd="curl -s --form-string \"token=$apptoken\" "
cmd+="--form-string \"user=$user_key\" "
cmd+="--form-string \"message=$string\" "
if [ -f "$1" ]; then cmd+="-F \"attachment=@${1}\" "; fi
cmd+="https://api.pushover.net/1/messages.json > /dev/null"

# Execute!
eval $cmd