Running strerror() from the shell

Reasonably often, I have a need to convert an errno variable to its string error message right at the shell.  This seems to come up relatively often in kernel development, but occasionally elsewhere.  Where I can, I usually just go for a printf(“Error: %mn”Smilie: ;) or printf(“Error: %sn”, strerror(foo)) directly in the debug statement I’m adding.  However, %m doesn’t work in the kernel and occasionally I either want or have to avoid recompiling something that just prints the integer value.  Chasing the header file chain to figure out what a given error code is can be time consuming and silly, but I’ve done it.

Recently, I’ve been trying to notice when I do stupid things repetitively and take the time to write a helper script or shell alias to prevent wasting effort the next time I need to do a particular task.  I have a collection of shell aliases, but I also keep a ~/bin directory with helper scripts for things that fit that mold better.  To solve my errno issue, I wrote the following today and stored it in ~/bin/perror:


import os
import sys

for i in sys.argv[1:]:
    i = abs(int(i))

    print “%3i: %s” % (i, os.strerror(i))

It could probably be done smaller in a shell alias that calls perl or something, but oh well.  This is pretty handy so I can quickly get a couple of values:

% perror 111 22
111: Connection refused
 22: Invalid argument

I’ve already used it several times today, so it was definitely worth the 2 minutes it took to codify it.

Category(s): Codemonkeying

Comments are closed.