Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if program exists in Bash Script - abbreviated version

I want to use the abbreviated if then else to determine if ccze exists before using it... and I just cannot get that first part right...

test() {
    [  $(hash ccze) 2>/dev/null ] && echo "yes"  || echo "no"
}

The above is just test.. what am I doing wrong? It does not matter if ccze exists or not - I'm getting "no"

like image 968
Peter Scargill Avatar asked Dec 07 '25 08:12

Peter Scargill


1 Answers

testcmd () {
    command -v "$1" >/dev/null
}

Using it:

if testcmd hello; then
    echo 'hello is in the path'
else
    echo 'hello is not in the path'
fi

or

testcmd man && echo yes || echo no

or you could put that into a function:

ptestcmd () {
    testcmd "$1" && echo 'yes' || echo 'no'
}

This way you'll have one function that does testing and a separate function that does printing dependent on the test result. You may then use the one taht is appropriate for the situation (you may not always want output).

like image 173
Kusalananda Avatar answered Dec 09 '25 22:12

Kusalananda