Archive for January, 2009

Dangerous Shell Scripts

Tuesday, January 13th, 2009

I’ve seen a few shell scripts recently which use environment variables to determine installation paths etc so that the script Just Works when run.

This is generally desirable but the importance of checking the environment variables before doing anything should not be overlooked. Consider the following (admittedly contrived!) example:

#!/usr/bin/env bash

# uninstall product
PRODUCTROOT="${INSTALLROOT}/${PRODUCTNAME}"

rm -rf "${PRODUCTROOT}"

The script assumes INSTALLROOT and PRODUCTNAME are set but it doesn’t verify this. If they’re not, the effective behaviour is:

rm -rf "/"

(Please don’t try that out!)

While it’s not possible for a deletion script to really know whether or not you meant to delete something, it can at least check the preconditions.

To check that the necessary variables are set:

#!/usr/bin/env bash

function check_env_vars() {
  local var_list=$@
  for var_name in ${var_list[@]}; do
    eval var_value="\$$var_name"
    if [ -z "${var_value}" ]; then
      echo "${var_name} must be set!" >&2
      exit 1
    fi
  done
}

check_env_vars INSTALLROOT PRODUCTNAME

# if we get this far, the variables are set
# you could change the exit to return an error status
# instead and trap it here

Tracing Objective-C method calls

Friday, January 2nd, 2009

There are probably more clever ways to do this, but as a quick and dirty hack I find this useful for finding out which methods are being, or could potentially be, called on my object:

- (BOOL)respondsToSelector:(SEL)aSelector
{
  NSLog(@"respondsToSelector:'%s'", sel_getName(aSelector));
  return [super respondsToSelector:aSelector];
}