user3341592
user3341592

Reputation: 1561

Best way to define "conditional" aliases in shell

What's the best way to define an alias if, let's say, "ag" executable is found?

if (( $+commands[ag] )) ; then alias grep='ag'; fi

or

[[ -s $(which ag) ]] && alias grep='ag'

or

if $(which ag >& /dev/null); then alias grep='ag'; fi

or ...?

By best, I mean more robust, more performant and/or more portable (Bash, Zsh).

What's your advice?

Upvotes: 19

Views: 5258

Answers (2)

tripleee
tripleee

Reputation: 189437

I don't see how the simple obvious POSIX variant would have any drawbacks compared to the (mostly non-portable) alternatives you propose.

type ag >/dev/null 2>&1 && alias grep=ag

Upvotes: 20

Jens
Jens

Reputation: 72657

I use this pathto function for portability to all Bourne heritage shells (I don't use which because it is not in POSIX so its output format is unspecified and it complains when nothing is found instead of being silent):

pathto () {
        DIRLIST=`echo $PATH|tr : ' '`
        for e in "$@"; do
                for d in $DIRLIST; do
                        test -f "$d/$e" -a -x "$d/$e" && echo "$d/$e"
                done
        done
}

which echos the pathname for any executable given when found, along with

test "`pathto less`" != "" && alias more=less

As for performance, you shouldn't care because the number of times you call pathto is negligible. Your first two examples use the non-portable (( )) and [[ ]] constructs and should be avoided.

Note also that I don't specifically deal with empty parts in PATH. For security reasons they should be avoided, just like ..

Upvotes: 1

Related Questions