Best way to define "conditional" aliases in shell
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 .
.