The question is not quite clear:
- Do you want to test if some string corresponds to an executable command?
or
- Do you want to test if a file is executable
You want to test if a file is executable
The -x
test is useful in the second case because it tests whether a given file is executable, i.e., if the executable bit is set.
It requires you to provide a valid file name. Unless you provide a full file path, the current directory is searched. Thus your command will typically fail for e.g. cp
, unless you first make the directory of the executable current, i.e. cd /usr/bin
.
To retrieve the full file path of an executable, you can use the shell build-in type
with the options -P
so only a matching executable in the search PATH
is retrieved (ignoring aliases, hashed commands and functions). Note that that may not be what is executed on the system by default.
You could also add an action to execute if the test fails. Then your statement becomes:
[[ -x $(type -P cp) ]] && echo YES || echo NO
which can also be written as
test -x $(type -P cp) && echo YES || echo NO
You want to test if some string corresponds to an executable command
If your question aimed to ask how to test if something is an executable command on your system, just use type
:
type ls &>/dev/null && echo YES || echo NO
Type will return an error code if the string does not correspond with something executable, so the second command will not be executed.