Shell 测试以查看二进制文件是否在您的路径中

发布于 2024-11-03 19:40:27 字数 448 浏览 1 评论 0原文

在 csh、tcsh、bash、perl(等)中,您可以进行同等测试(不一定使用相同的语法):

test -e PATH; # Does PATH exist
test -f PATH; # Is PATH a file
test -d PATH; # is PATh a directory
...

是否存在类似的构造来检查二进制文件是否在您的路径中? (也许是否存在别名,甚至是内置的)

显然,这可以通过以下形式来完成:

#!/usr/bin/env bash
C=COMMAND;
test $(which $C) -o $(alias $C) && "$C exists"

或在其他 shell/脚本语言中类似的东西。

问题不在于是否可以测试程序、命令等是否存在。问题在于是否存在内置测试。

In csh, tcsh, bash, perl (etc) you can do tests on par with (not necessarily with the same syntax):

test -e PATH; # Does PATH exist
test -f PATH; # Is PATH a file
test -d PATH; # is PATh a directory
...

Does a similar construct exist for checking whether a binary is in your path? (and perhaps whether an alias, or even a built-in exist)

Obviously this can be done with something of the form:

#!/usr/bin/env bash
C=COMMAND;
test $(which $C) -o $(alias $C) && "$C exists"

or something similar in other shells/script languages.

The question isn't whether it's possible to test for the existence of a program, command, etc. The question is whether a built-in test exists or not.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦巷 2024-11-10 19:40:27

从技术上讲,如果您只是在当前 PATH 中查找内容,那么唯一真正的解决方案是第二个代码块的第一部分:

which $C

which是当前 PATH 中唯一真正符合您的实际要求的,因为 whereis 将在路径之外搜索:

whereis ...尝试在标准 Linux 位置列表中找到所需的程序。

来自 whereis(1)

alias 当然与实际的可执行文件无关,而是 shell 环境中的别名命令

所以,实际上,您已经有了正确的方法,只是要小心,您知道 whereis 可能不会对测试链有帮助。

Technically if you're just looking for stuff in the current PATH then the only real solution is the first portion of your second code block:

which $C

which is the only one that really fits your actual requirement of in the current PATH as whereis will search outside the path:

whereis ... attempts to locate the desired program in a list of standard Linux places.

from whereis(1)

and alias of course has nothing to do with actual executables, but rather aliased commands within your shell environment

So, really, you've got the right approach already, just be careful that you know that whereis may not be a helpful addition to that chain of tests.

铁憨憨 2024-11-10 19:40:27

或者只是:

type -P awk   # returns the first matched binary called 'awk' in current PATH

Or just:

type -P awk   # returns the first matched binary called 'awk' in current PATH
蓝戈者 2024-11-10 19:40:27

另一种解决方案是

find $(echo $PATH|tr : \ ) -maxdepth 0 -executable -name Executable

“Executable”是所需应用程序的名称。
例如:

find $(echo $PATH|tr : \ ) -maxdepth 0 -executable -name awk

返回

/usr/bin/awk
/bin/awk

An alternative solution is

find $(echo $PATH|tr : \ ) -maxdepth 0 -executable -name Executable

Where Executable is the name of the wanted application.
For example:

find $(echo $PATH|tr : \ ) -maxdepth 0 -executable -name awk

returns

/usr/bin/awk
/bin/awk
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文