[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: aliases versus functions



On Sat, Jun 07, 2003 at 12:04:44AM -0700, Vineet Kumar wrote:
> Functions allow you to use parameters, simple branching ("return"),
> recursion, local variables.  Functions allow you recursion, as well.
> The only real reason that this means you should use them instead of
> aliases is that there's no real reason not to; you get to use those
> features if you want to (at no cost to you if you don't).  If you always
> use either one or the other, you don't have to worry about the different
> behaviors of how they're expanded and applied.  Since always using
> aliases is insufficient, you should use aliases if you always use one or
> the other.

A friend of mine thought about this [1] for a bit and worked out that
there is actually something aliases can do that functions can't: because
they're expanded textually before things like wildcard expansion happen,
it's possible to use aliases to fiddle temporarily with the lexical
structure of your shell.

The example he gave was this:

    thisway() { cd subdir; ls -l "$@" }
    alias thatway='cd subdir; ls -l'

  Without any arguments, or with ordinary non-wildcard arguments, both
  these functions do the same thing. But pass the argument `*' and the
  behaviour will be very different - and in this particular case, the
  alias's behaviour will probably be more useful.

With a bit of contorted syntax, you can do more complicated things by
defining a helper function inside the alias. Simon gave this (not
production-quality) example:

  alias globelsewhere='
    f() { echo "$@"; cd $olddir; unset olddir; unset f; }
    olddir=$PWD; cd /etc; f'

I actually have this one in my bash configuration, to disable wildcard
expansion for the arguments of 'find'. It could probably do with a
'trap' command to make sure that wildcard expansion is restored even if
the function is terminated abruptly.

  alias find='_find() { find "$@"; set +f; unset _find; }; set -f; _find'

It's all quite a sick hack - but a remarkably useful one at times.

[1] http://www.livejournal.com/users/simont/29549.html

-- 
Colin Watson                                  [cjwatson@flatline.org.uk]



Reply to: