开发者

find a command on $PATH

I'm writing a script, and I need to look up a command on the user's $PATH and get the full path to the command. The problem is that I don't know what the user's login shell is, or what strange stuff might be in their do files. I'm using the bourne shell for my simple little script because it needs to run on some older Solaris platforms that might not have bash.

Some implementations of "which" and "whence" will source the user's dot files, and that isn't really portable to all users. I'd love a simple UNIX utility that would just do the basic job of scanning PATH for an executable and reporting the full path of the first match.

But I'll settle for any /bin/sh solution that is stable for all users.

I'm looking for a solution that is better than writing my own /bin/sh loop that chops up $PATH and searches it one line at a time. It would seem that this is common enough that there should be an reusable way to do it.

My first approximation of the开发者_StackOverflow社区 "long way" is this:

   IFS=:
   for i in $PATH; do
      if [ -x $i/$cmd ]; then
          echo $i/$cmd
      fi
   done

Is there something simpler and portable?


The answer seems to be the 'type' built-in.

% /bin/sh
$ type ls
ls is /bin/ls


Maybe the whereis command will work for you?

whereis -b -B `echo $PATH | sed 's/:/ /g'` -f [commands]

e.g. on my computer, this works:

whereis -b -B `echo $PATH | sed 's/:/ /g'` -f find man fsc

And results in:

find: /usr/bin/find
man: /usr/bin/man
fsc: /opt/FSharp-2.0.0.0/bin/fsc.exe /opt/FSharp-2.0.0.0/bin/fsc

One caveat from the whereis man page:

   Since whereis uses chdir(2V) to run faster, pathnames given
   with the -M, -S, or -B must be full; that is, they must begin
   with a `/'.


This question is answered in details here: https://unix.stackexchange.com/questions/85249/why-not-use-which-what-to-use-then. Bottom line: use command -v ls.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜