Conditionals :: Bash

Numeric Comparisons

$ x=0
$ y=1
$ ((x >= 1)) && echo YEP || echo NOPE
NOPE
$ ((y >= 1)) && echo YEP || echo NOPE
YEP

Check If Executable

Does not work:

$ [[ -x cp ]] && echo YES || echo NO
NO

One must specify the full path:

$ [[ -x /bin/cp ]] && echo YES || echo NO
YES

Or using which if path is not known:

GNU coreutils on a macOS system
$ which ls
/usr/local/opt/coreutils/libexec/gnubin/ls

$ [[ -x $(which ls) ]] && echo YES || echo NO
YES

Or using bash’s type buil-in:

$ if [[ -x "$(type -fP curl)" ]] && echo YES || echo NO

But it fails as curl takes at least an URL parameter. The most recommended way is using bash’s command built-in:

$ [[ command -v curl ]] && echo YES || echo NO
-bash: conditional binary operator expected

But we can’t use it inside [[ ]] or if test …​ or if [ …​ ]. It has to be something like this:

if command -v curl 1> /dev/null
then
  echo YES
else
  echo NO
fi