Wednesday, 29 March 2006

Shell script wrappers

Sometimes a bash script needs to invoke another program, but for temporary compatability reasons needs to override some environment variables to affect it’s behaviour.
A common way is to do this:

flanger() {
  MODE=compat /usr/bin/flanger "$@"
}

flanger-test() {
  MODE=compat /usr/bin/flange-test "$@"
}

and then call flanger as normal.

I had a case where this kept cropping up so I finally wrote this:

env_wrap() {
  local env=""



  # collect VAR=VALUE pairs for environment
  while :
  do
    case "$1" in
      *=*) env="$1 "; shift;;
      *) break;;
    esac
  done



  for prog in "$@"
  do
    eval "$prog() { $env `type -p $prog` \"\$@\"; }"
  done
}


Now I just do

env_wrap MODE=compat flanger flange-test

And it’s all taken care of

1 comment:

  1. Of course, rather than use `type -p ...` I could have used the literal: command ...

    which causes the shell to invoke an external command instead of shell function, but I didn't know that at the time.

    ReplyDelete