[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Bug#291026: Use of command -v



>     if [ -x "$(command -v foo 2>/dev/null)" ] ; then

It should be pointed out that this workaround can fail if foo is a
shell function.  In that case, "command -v foo" prints "foo" and
[ -x "foo" ] tests for the executability of ./foo.  If ./foo is absent
then the test fails even though foo is an executable shell function.
On the other hand, if only commands on the PATH are desired, then
foo being defined and ./foo being present causes the test to succeed
even though there is no foo on the PATH.

Consequently it should be mentioned in 9.3.3.2 that foo (or, rather,
invoke-rc.d in the example there) must not be a shell function.

Either that or the code needs to be tightened up so that executability
is only tested-for if the output of "command -v" is not a shell function
name.

The output of "command -v" is not a shell function name if it begins
with a slash or a dot.  Thus to execute either shell functions or
commands on the PATH:

   if CMD="$(command -v foo 2>/dev/null)" \
      && { \
         { [ "${CMD#.}" = "$CMD" ] && [ "${CMD#/}" = "$CMD" ] ; } \
         || [ -x "$CMD" ] ; \
      }
    then
      foo ...

Alternatively, to execute only commands on the PATH:

   if CMD="$(command -v foo 2>/dev/null)" \
      && { [ "${CMD#.}" != "$CMD" ] || [ "${CMD#/}" != "$CMD" ] ; } \
      && [ -x "$CMD" ]
    then
      foo ...

The type command could be used here but I understand that its
implementation depends on the shell.

Another option would be to replace "command -v" with "findcommand" along
with the definition of that function posted by Tollef Fog Heen in
#218530.  This works only for commands on the PATH, not for shell
functions.

~---------------------------------------------------------

The following is beginning to seem like a better alternative:

    foo || case "$?" in 126|127) do_alternative_to_foo ;; esac

The one problems is that this prints an unwanted:

    bash: foo: command not found

if foo is not executable.  Do particular shells provide some means of
switching that message off?

-- 
Thomas Hood <jdthood@aglu.demon.nl>




Reply to: