[ACCEPTED]-Find out if a command exists on POSIX system-posix
command -v
is a POSIX specified command that does 3 what which does.
It is defined to to return 2 >0 when the command is not found or an error 1 occurs.
You could read the stdout/stderr of "which" into 9 a variable or an array (using backticks) rather 8 than checking for an exit code.
If the system 7 does not have a "which" or "where" command, you 6 could also grab the contents of the $PATH 5 variable, then loop over all the directories 4 and search for the given executable. That's 3 essentially what which does (although it 2 might use some caching/optimization of $PATH 1 results).
Actually, which
is a shell script available in 11 git repository. The script seems to be POSIX compatible 10 and you could use it, if you take into account 9 copyright and license.
command -v
as such is problematic 8 as it may output a shell function name, an 7 alias definition, a keyword, a builtin or 6 a non-executable file path. On the other 5 hand some path(s) output by which
would not be 4 executed by shell if you run the respective 3 argument as such or as an argument for command
.
A 2 POSIX shell function using command -v
could be something 1 like
#!/bin/sh
# $1 should be the basename of the command to be found.
# Outputs the absolute path of the command, or returns 1, if there is no
# such command in PATH executable by the caller and not shadowed by
# alias, builtin, keyword or shell function.
executable() {
if cmd=$(unset -f -- "$1"; unalias -a; command -v -- "$1") \
&& [ -z "${cmd##/*}" ] && [ -x "$cmd" ]; then
printf '%s\n' "$cmd"
else
return 1
fi
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.