3

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"

1
  • 1
    Try without the square brackets Commented Sep 1, 2017 at 11:47

4 Answers 4

5
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).

Sign up to request clarification or add additional context in comments.

Comments

2

Suggestion #1 - Answer

some_function() {
  hash ccze &> /dev/null && echo "yes" || echo "no"
}

Suggestion #2

Rename the function to something else because there is already the command test.

Don't override.

Suggestion #3

Remove the square brackets. Even if, in any case, you want to use square brackets, use double square brackets. Single square brackets are deprecated.

Brain Food

Comments

0
test() #(not a good name)
{
    if hash ccze 2>/dev/null; then
       echo yes
    else 
       echo no
    fi
}

should do it.

command -v ccze >/dev/null is also usable and fairly portable (not POSIX but works with most shells).

Comments

0

Thanks for that but it was the one liner I wanted. I know that version works.

Meanwhile we figured it out...

test() { [ -x "$(command -v cckze)" ] && echo "yes" || echo "no"; }

Thanks anyway.

2 Comments

If you want swift scripts, you should skip needless process substitution and IO. have_command(){ command -v cckze >/dev/null; } or if you need the IO have_command(){ command -v cckze >/dev/null && echo yes || echo no; }
You should call your function something other than test to avoid overriding the test utility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.