I'm not entirely sure I understand what you're after either but type
and which
should help. For example:
$ type -a sudo
sudo is aliased to `/usr/bin/sudo'
sudo is /home/terdon/scripts/sudo
sudo is /usr/bin/sudo
In the example above, there are 3 possible sudo
s, one is an alias and two are in my $PATH
. You can just parse that to do what you want. If you are using a shell that does not have the type
builtin, you can do the same with which
(though that does not detect aliases but that shouldn't be an issue with shell scripts anyway.):
$ which -a sudo
/home/terdon/scripts/sudo
/usr/bin/sudo
With this in mind, if your objective is to avoid an infinite loop based on the name of the current script, you can do something like:
#!/usr/bin/env bash
## Get the name of the matching command from your
## $PATH, excluding the script itself ($0).
com=$(type -a $(basename $0) | grep -v $0 | head -n 1 | awk '{print $NF'})
## Run the command on the arguments passed
$com "$@"
As @edimaster pointed out in the comments, -a
is not defined by POSIX so it may not be present in all systems. A more portable approach then, would be to search through the directories of your $PATH
:
#!/usr/bin/env bash
## Get the name of the matching command from your
## $PATH, excluding the script itself ($0).
com=$(find $(printf "%s" "$PATH" | sed 's/:/ /g') -name $(basename $0) |
grep -v $0 | head -n 1)
## Run the command on the arguments passed
$com "$@"