Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Best practices for managing aliases in ohmyzsh?



On Tue, Aug 31, 2021 at 5:52 PM Steve Dondley <s@xxxxxxxxxxx> wrote:
>
> But I'm a little confused on a point you made. What do you consider the
> difference to be between a script and a function?

By script I mean an executable file, a.k.a. an external command or utility.

If you run `type foo` and it says "foo is a shell function" then it's
a function. If it says `foo is /bin/foo`, then it's an executable
file. Executable files written in interpreted languages are scripts.

Many utilities can be implemented either as functions or as scripts.
Here's an example:

    % rm foo
    % >foo <<<'echo "I am a script"'
    % chmod +x foo
    % path+=($PWD)
    % function bar() echo "I am a function"
    % type foo
    foo is /tmp/foo
    % type bar
    bar is a shell function
    % foo
    I am a script
    % bar
    I am a function

All utilities that can be implemented as scripts can also be
implemented as functions but there are utilities that can be
implemented as functions but not as scripts. For example, here's a
function I use often:

    function md () {
      (( ARGC == 1 )) && mkdir -p -- "$1" && cd -- "$1"
    }

Upon executing `md /tmp/foo` I expect my current directory to be
/tmp/foo. This cannot work if md is a script.

So functions can do things that scripts cannot. Another advantage is
that they are faster to execute by 1 millisecond or so. Other than
that, scripts are better. They are much more resilient to changes in
your environment and won't break when you change options in your
interactive shell, define aliases, change shells, etc. Writing
functions that reliably work in interactive shells is not too hard but
it's definitely an advanced skill.

So the rules of thumb are:

1. If it cannot be a script, it has to be a function. Duh.
2. If it can be a script and 1ms overhead doesn't matter, it should be a script.

Always remember to add a shebang to your scripts. Since your scripts
are known to work in bash, start all of them with this line:

    #! /usr/bin/env bash

> [snip shell code]
>
> Do you consider this to be a function or a script?

If you put this in an executable file in your PATH, it'll be a script.
I recommend doing that. You can also create a function with that body
but that would be worse.

> I don't call this function directly, it is only called from an alias

Aliases can invoke scripts just as easily as they can invoke functions.

Roman.




Messages sorted by: Reverse Date, Date, Thread, Author