Twitter is one of the biggest and fastest-growing social media sites currently online. If you’re not already “tweeting,” you should know that Twitter is a micro-blog: short little posts, called tweets, allow you to share what you are doing or thinking with others. The posts are 140 characters at a maximum, and you can follow other people on Twitter, as well as have other people follow you.

A number of companies and projects are starting to use Twitter as a means of making announcements, which means that you can follow projects or organizations that interest you to see what is going on with them. Twitter is a Web-based service, so you log in to tweet and to look at the folks you are following. Through its available API, however, you can use other clients to send your tweets and read Twitter.

If you are more interested in sharing your thoughts or project announcements than in reading other people’s tweets, there is a very easy way to accomplish this: using the command-line.

The script you will see takes exactly one argument: your tweet. You use it like this:

$ ~/bin/tweet "Writing my TechMails"
Successful tweet!

Once you run the script and look on Twitter, your post is there for all to see. The script itself uses nothing fancier than cURL to post the text provided to the script. The text must observe shell constraints: it must be properly escaped for special characters (such as “!” and “?”). The script doesn’t require the tweet to be in quotes; you could use:

$ ~/bin/tweet Does my tweeter need quotes\?
Successful tweet!

and it would work just as well.

The script itself:

#!/bin/sh
tweet="${@}"
user="username"
pass="sekret"
if [ $(echo "${tweet}" | wc -c) -gt 140 ]; then
    echo "FATAL: The tweet is longer than 140 characters!"
    exit 1
fi
curl -k -u ${user}:${pass} -d status="${tweet}" https://twitter.com/statuses/update.xml >/dev/null 2>&1
if [ "$?" == "0" ]; then
    echo "Successful tweet!"
fi

Output of the cURL command is directed to /dev/null because it returns some XML that we don’t need to care about. The script also makes sure that the tweet is 140 characters or less, and exits with an error if it is longer.

The applications for this very simple script can be quite interesting. You could hook this into a subversion repository to notify of new commits to your project or you could put together a script to take the title of a new regular blog post and turn it into a tweet using a URL shortening service to generate a link — there are a number of ways to automate interesting things with this script.

Get the PDF version of this tip here.