在 $PATH 上查找命令
我正在编写一个脚本,我需要在用户的 $PATH 上查找命令并获取该命令的完整路径。问题是我不知道用户的登录 shell 是什么,或者他们的 do 文件中可能有什么奇怪的东西。我使用 bourne shell 来编写简单的小脚本,因为它需要在一些可能没有 bash 的旧版 Solaris 平台上运行。
“which”和“whence”的某些实现将获取用户的点文件,但这并不是真正适合所有用户。我想要一个简单的 UNIX 实用程序,它只执行扫描可执行文件的 PATH 并报告第一个匹配的完整路径的基本工作。
但我会选择任何对所有用户都稳定的 /bin/sh 解决方案。
我正在寻找一种比编写自己的 /bin/sh 循环更好的解决方案,该循环会切碎 $PATH 并一次搜索一行。这似乎很常见,应该有一种可重用的方法来做到这一点。
我对“漫长的道路”的第一个近似是:
IFS=:
for i in $PATH; do
if [ -x $i/$cmd ]; then
echo $i/$cmd
fi
done
有没有更简单和便携的东西?
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 "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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
答案似乎是内置的“类型”。
The answer seems to be the 'type' built-in.
也许
whereis
命令适合您?例如,在我的计算机上,这有效:
并导致:
whereis
手册页中的一个警告:Maybe the
whereis
command will work for you?e.g. on my computer, this works:
And results in:
One caveat from the
whereis
man page:这个问题在这里详细回答:https://unix。 stackexchange.com/questions/85249/why-not-use-which-what-to-use-then。底线:使用
命令 -v ls
。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
.