Frage

Problem

I may or may not have the executable thing in my $PATH.

How can I neatly check this in a ZSH script?

Existing Attempt

I just run the command, sending the output and errors or noman's land, then check the result code.

thing > /dev/null 2>&1
thing_installed=$?
if [ $thing_installed -eq 0 ]; then
    echo 'Thing Installed!'
fi

I feel like this could be done more neatly (one liner?).

War es hilfreich?

Lösung

In zsh, which behaves reasonably, so you can simply do

if which thing > /dev/null 2>&1; then
    echo installed
fi

or

which thing > dev/null 2>&1 && echo installed

Note that which is a shell builtin, and its behavior is not reasonable in all shells, so this behavior cannot be relied upon.

Andere Tipps

For zsh whence is the tool you are looking for. With parameter -p it can be forced to look only in $PATH and ignore functions, builtins and aliases with the same name.

This will either return the path to thing or an error message:

whence -cp thing

use which thing and check result code

You can check whether the file exists by this expresion:

[ -e thing ] && echo 'Thing Installed!'

The -e operator checks whether the file exists or not. If you want to do other file tests take a look to this page: http://tldp.org/LDP/abs/html/fto.html.

Hope this was helpful ;-)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top