Thursday, March 22, 2012

Prowl Push Notifications from Bash

After Matt Richardson finally convinced me to buy the Prowl app for iOS, which allows you to send Push notifications to iOS devices using nothing but their simple http API, I've started trying to build it into everything.  I have all sorts of bash scripts running on my computers which rotate logs, check system health, run backup scripts, etc, and why just have them send me emails to my user account, when I can have them send text messages to my iPod?

Of course, the thing is, I very quickly got tired of having to copy-paste the same magic curl command into every script where I wanted to use it, so I wrote this quick little wrapper script around it to make it a little easier to use Prowl on my computer, and make my bash scripts a little easier to read.

To install this on your computer, make sure that you have curl installed (or rewrite this for wget, which is more likely to be installed by default), and then paste this code into a file somewhere in your shell's PATH list (which is where your shell looks for commands when you type one in).  If this is your personal computer, you could get away with putting this in /usr/bin, but I append ~/bin/ to my PATH so I can keep my personal scripts there.  chmod +x filename to make it executable, and replace my censored API key with your own from prowl's website.

Source code:

Two things that this script uses which is a little squirrely is the $# built-in variable and the /dev/fd/2 device.

$# is a special variable in bash which is the number of arguments passed to a script, so in this case I am using it to see if the user is calling prowlpost with two or three arguments to decide if they're trying to change the priority of the message from the default, or otherwise try and explain to them again how to use this tool if they don't manage to give either two or three arguments.

The reference to /dev/fd/2 around line 32 is part of the VFS which exposes the three standard streams (standard in, standard out, and standard error) as path names in your devtmpfs.  Since it is traditional for usage problems with a script to be printed to standard error instead of the default standard out that echo uses (so the user is more likely to see them from commands in the middle of pipe chains), we redirect the output of echo to /dev/fd/2, which is a file descriptor for wherever stderr happens to go to for this script's shell as a whole.  It's a nice trick if you need to explicitly pipe things into stderr or stdout, or pipe stdin into something.

1 comment:

  1. Your >/dev/fd/2 is over complicated. You can use bash's native redirection feature.

    e.g.
    echo "test error" >&2

    ReplyDelete