How to quickly share source code snippets

I often have the necessity to share a long snippet of code with someone located somewhere who somehow needs it. Sure, there are a lot of services out there, ranging from Pastebin to Snipplr, but the point is that they waste way too much of my time: I have to visit the website, in some cases I’m forced to register/login, and so on. Spending a good amount of my time on the command line, I was looking for a much more convenient way to quickly share my code.

source code

I accidentally found sprunge.us, which is a very simple web app hosted on Google App Engine, that fulfills this purpose. By executing this command on the terminal:

$ cat <filename> | curl -F 'sprunge=<-' http://sprunge.us

where <filename> is the name of the file you want to share, you get something like:

http://sprunge.us/RJij

and the output is like this. Cool, uh? if you then append “?<extension>” to the resulting URL, where <extension> might be “js“, “html“, “sql“, “php“, or whatever else, you gain line numbering and syntax coloring, as shown here, which is way much pretty and clearer. Well, then why don’t we try to automate things a little bit? Fire your terminal and navigate into your ~ folder; here launch:

$ vi .zshrc

or

$ vi .bash_profile

depending on the shell you’re using. I use zsh, so I edited the .zshrc file. Press “i” to enter INSERT MODE and edit this file adding the following line:

function sprunge() { cat "$@" | curl -F 'sprunge=<-' http://sprunge.us ; echo "?${@##*.}" }

then press <ESC> and type “:wq” to save and exit vim. Then launch:

$ source .zshrc

or

$ source .bash_profile

depending on the file you’ve edited and open a new tab of the Terminal.

What we’ve basically said is: when I invoke the:

$ sprunge <filename>

command, take the filename passed as a parameter and read it, redirecting its content as an input to the “curl” command, which will fake a POST request to the form at the specified URL; when the output is returned, print the ‘?‘ character on a new line, followed by the extension of the filename passed as input, without the preceding dot. For example, if we invoke:

$ sprunge abstract.php

from the folder containing that file, we get something like:

http://sprunge.us/RJij
?php

This way, we can either copy only the first line in case we’re not interested in line numbering and syntax coloring, or everything starting from the end of the second line up to the beginning of the first line, having both lines concatenated in one single line, and share it. That’s it! How does it sound? :)

Advertisements