确定命令是否存在始终为 false

发布于 2025-01-13 07:38:13 字数 463 浏览 0 评论 0原文

MacOS 将 zsh 作为默认 shell。

检查命令是否存在的代码:

if command -v omz
then
    echo "exists";
else
    echo "does not exists";
fi

运行它,它总是返回为不存在(使用安装/卸载进行测试)。

但是,如果我在 shell 中输入以下内容:

$ ./test.sh
does not exists

$ omz
[prints out help dialigue]

$ command -v omz
omz

我尝试了不同的测试方法,但总是相同的。


omz 随 Oh-my-zsh 一起提供,我用它来确定 Oh-my-zsh 是否安装在我的自动化脚本中。检查这个的正确方法是什么?

MacOS has zsh as the default shell.

The code to check if a command exists:

if command -v omz
then
    echo "exists";
else
    echo "does not exists";
fi

Run it and it always comes back as does not exist (tested with installed/uninstalled).

However, if I type the following in a shell:

$ ./test.sh
does not exists

$ omz
[prints out help dialigue]

$ command -v omz
omz

I tried different ways of testing, always the same.


omz ships with Oh-my-zsh and I'm using it to determine if Oh-my-zsh is installed in my automation scripts. What would be the correct way to check this?

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

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

发布评论

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

评论(2

分开我的手 2025-01-20 07:38:13

确定命令是否存在始终为 false

omz 是一个 shell 函数

这是一个 shell 函数。 Shell 函数不会导出。据我所知,在 ZSH 中不可能导出 shell 函数。

命令失败,因为没有这样的命令。

始终为假

它并不总是假的。创建一个名为 omz 的可执行文件并将其放入您的 $PATH 中 - 当然,command -v 将返回成功。

或者,定义 omz 函数或获取提供 omz 定义的文件,然后再检查它是否存在。

问题是如何成功测试这个函数是否存在?

你正在这样做。该函数在您的脚本中不存在,因此您已成功测试该函数不存在。测试工作。

如果你想专门测试它是否是一个函数,请使用 match type 输出,例如 case "$(type omz)" in *shell\ function*) echo it is; ;; *)回显它不是; ;; esac。

Determinate if command exists is always false

omz is a shell function

It's a shell function. Shell functions are not exported. As I read, it is not possible in ZSH to export a shell function.

command fails, because there is no such command.

is always false

It is not always false. Create an executable named omz and put it in your $PATH - for sure, command -v will return success then.

Or alternatively, define omz function or source the file that provides omz definition, before checking for it's existence.

The question is how to successfully test that this function exists?

You are doing that. The function does not exist in your script, ergo you are successfully testing that the function does not exist. The test work.

If you want to specifically test if it is a function, use match type output, like case "$(type omz)" in *shell\ function*) echo it is; ;; *) echo it is not; ;; esac.

自此以后,行同陌路 2025-01-20 07:38:13

这个怎么样?

zsh 的内置 which 没有 -s(静默)选项,请使用 /usr/bin/which

#!/bin/sh
if /usr/bin/which -s $1
then
    echo "exists"
else
    echo "not exists"
fi

how about this?

zsh's build-in which have not -s(silent) option, use /usr/bin/which.

#!/bin/sh
if /usr/bin/which -s $1
then
    echo "exists"
else
    echo "not exists"
fi
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文