Home > Software engineering >  Determinate if command exists is always false
Determinate if command exists is always false

Time:03-11

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related