Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How can I check if a program exists from a Bash script?

How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?

It seems like it should be easy, but it's been stumping me.

Answer*

Draft saved
Draft discarded
Cancel
5
  • Doesn't work. test -x $(which ls) returns 0, as does test -x $(which sudo), even though ls is installed and runnable and sudo is not even installed within the docker container I'm running in. Commented Feb 20, 2019 at 2:26
  • 2
    @algal You need to use quotes I think, so test -x "$(which <command>)" Commented Apr 2, 2019 at 12:19
  • @algal Perhaps ls is aliased? I dont think it would work if the command has parameter. Commented Apr 2, 2019 at 15:38
  • I can't vouch for this answer, but I'd also recommend quotes. $ test -x $(which absent_cmd) returns test: too many arguments, while test -x "$(which absent_cmd)" is properly parsed and results in exit code 1. Commented Dec 17, 2020 at 18:13
  • 2
    @acorello, the test: too many arguments suggests that which absent_cmd returns a multi-word error message. An executable file having the same name as the message could exist. 😁 Using which this way is just a bad idea. Commented Dec 23, 2021 at 14:57

lang-bash

AltStyle によって変換されたページ (->オリジナル) /