OSX Sharing Name

May 26 2005 Kelly Norton

?Like most geeks, a healthy portion of my desktop space is consumed by meticulously aligned command shells. I'm always flipping from shell to shell (thanks to iTerm) and usually from machine to machine. As a result, my shells all bear the usual geek branding of the personalized prompt which includes an abbreviation of the computer's name so I don't execute a command on the wrong machine (in my experience, that can have undesirable consequences).

This a pretty common practice among command shell users, but it's not always very informative. All my machines these days, have their addresses automatically assigned via DHCP. Often times, this causes the “hostname” for that computer to take on something like dhcp-23-208.media.mit.edu which at first glance doesn't really tell me what I want to know. This is especially true when you are using 15 machines that all begin with “dhcp-23-”. There are many different ways of dealing with this, many involve convincing the computer that it's name is actually something a little more recognizable. That can often have unintended consequences, however, if you are running any kind of server that depends on the computer name being recognizable to other computers.

On OSX, there is a computer name that can be set through the System Preferences panel that is used to identify the computer on the local file sharing network. As it turns out, that name on my machines is a lot more recognizable because it is a name that I picked by hand. My machine at home is flint while the one at the lab is ocmulgee (named after rivers in Georgia). Since I started using a Mac, back in August, I've always wanted that name to appear on my command prompt instead of the system hostname. Earlier this week, I had a couple of days to learn Objective-C and it turns out that getting a command line tool that does exactly what I need requires only a few lines of code.

So for what it's worth, here's some code to get OSX's computer name as it appears in the Sharing panel in System Preferences. I simply call this command in my .bashrc startup script and use the value as part of my prompt.

#import <Foundation/Foundation.h> 
#include <stdio.h> 

int main(int argc, char* argv[]) {
  int i;
  const int           npths = 4;
  const NSString      *pths[] = {


  NSAutoreleasePool   *pool = [NSAutoreleasePool new];
  NSString            *pref = [NSOpenStepRootDirectory()
  if (![[NSFileManager defaultManager] fileExistsAtPath:pref])
      return 1;
  NSObject            *dict
    = [NSMutableDictionary dictionaryWithContentsOfFile:pref];
  for (i=0;i<npths;i++) {
    dict = [(NSDictionary*)dict objectForKey:(NSString*)pths[i]];
    if (!dict)
      return 1;
  printf("%s\n",[(NSString*)dict UTF8String]);
  [pool release];
  return 0;