Unix & Linux
shell-script path portability alternatives
Updated Tue, 26 Jul 2022 22:51:29 GMT

search a command in PATH with the same name of the script


For example, my script is $HOME/bin/sudo. I'd like to search for an executable in $PATH with the same name, sudo, and run it - but not the script $HOME/bin/sudo itself, otherwise I will run into an infinite loop!

EDIT: the point of this is that in some cases i want my replacement scripts to have an higher priority over the regular system commands, while in some other cases i want the opposite. So i've set "$HOME/bin" as first in the PATH, so now i can define priorities for each command individually. Also i want some kind of "portability" so the scripts will be able to run in different systems.




Solution

POSIX defines the -p option to the command builtin so...

  • -p Perform the command search using a default value for PATH that is guaranteed to find all of the standard utilities.

Taken with the -v and -V options for either parsable or human-friendly (respectively) output regarding a command's location, and you can pretty well rely on it to get you the intended utility when you ask it for one. Here's a little script to demo how it works:

(   cd ~; mkdir -p bin
    cat >./bin/cat
    chmod +x ./bin/cat
    export "PATH=$HOME/bin:$PATH"
    command -V cat | cat
) <<\NOTCAT
#!/bin/sh
command -p cat
! printf "I'm not REALLY cat, but '%s' is!\n" \
         "$(command -pv cat)"
NOTCAT

OUTPUT

cat is /home/mikeserv/bin/cat
I'm not REALLY cat, but '/bin/cat' is!

The first couple statements build an executable script in ~/bin/cat. $PATH is also modified to insert ~/bin at its head.

So when I do command -V cat | cat command writes to my fake cat's stdin. And yet its output still makes it to my screen. This is because command -p cat gets the real one regardless of how I have mangled my $PATH.





Comments (2)

  • +1 – The only problem is that is guaranteed to find only the standard utilities, so it could not work in some cases. Btw this is a very concise solution using only POSIX standard features, so i prefer it over the others. (i just hope they won't change the syntax in later revisions ;) — Oct 26, 2014 at 16:36  
  • +0 – @eadmaster - this is a legitimate concern. However, if you look at man command, you'll find that in the Rationale they cite the purpose of finding the standard utilities is really to enable you always at least to do: command -p getconf PATH. — Oct 26, 2014 at 20:28