3

I am attempting to find a binary file in a Linux system using something like this:

if [ -f `which $1` ] then
    echo "File Found"
else
    echo "File not Found"
fi

while the code works fine the problem is "which" will return a null operator which BASH interprets as something existing so a file always comes back found. Any suggestions would be great.

Thanks

3 Answers 3

6

Update

After a bit more thought, there is no reason to use [[ ]] (or [ ] for that matter). There is even no reason to use command substitution either $()

if which "$1" > /dev/null 2>&1; then
  echo "found"
else
  echo "not found"
fi

If you're using bash then please use the [[ ]] construct. One of the benefits (among many) is that it doesn't have this problem

[[ -f $(which $1) ]] && echo found

Also, `` is deprecated, use $() instead

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

2 Comments

What are you rich? We don't just have square brackets to give away with these economic times.. (which "/bin/ls") .. silent on failure, prints the path on success.
@synthesizerpatel I think you meant hash "/bin/ls". But you're right, the new answer is sans two parens and four braces. Now everybody can afford to run it!
3
if [ `which "$1"` != "" ]; then

which won't return "" when it finds the binary.

Comments

1

I like 'hash' for this (if you're a bash user..) (and it's actually more portable behavior than which)

hash blahblah

bash: hash: lklkj: not found

hash /bin/ls <-- silently successful

This method works on Linux and OSX similarly, where-as 'which' has different behavior.

Comments

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.