Note: The Console blog is no longer active. I'm currently building the Sculpted Code blog, and when it's finished, I shall be posting there.
← Console Index
Determining OS Version in Dashboard Widgets

There are various times when you might want to know the version of the user’s operating system when performing some operation in your Dashboard Widget. While you can find it using AppleScript, there is a better way: the sw_vers Terminal command (which is located in /usr/bin/).

This is the output of the command on my computer at the time of writing:

ProductName: Mac OS X
ProductVersion: 10.5.4
BuildVersion: 9E17

Obviously, we need to extract the “10.5.4″ part.

I have done this by firstly extracting the “ProductVersion: 10.5.4″ part using a regular expression, and then deleting the “ProductVersion: ” part.

The resulting code is as follows:

widget.system("/usr/bin/sw_vers", function() {

 // Note that the "match" method returns an array.
 // The matched string, which is what we want,
 // is the first element in that array:

 var versionString = this.outputString.match(/ProductVersion:\t.*/)[0];

 // We delete the "ProductVersion: "
 // part by replacing it with nothing: 

 var version = versionString.replace("ProductVersion: ", "");
});