Check if a command exists in POSIX sh
Check that a command exists with command -v in POSIX sh. It is a builtin, it sees functions and builtins, and which does not.
Before using a tool, a script wants to know whether it is installed, and the answer should be the same in dash, Bash and BusyBox.
for c in git nosuchtool; do
if command -v "$c" >/dev/null 2>&1; then
echo "$c: found"
else
echo "$c: missing"
fi
done
command -v cd
which cd
echo "which exit status: $?"git: found
nosuchtool: missing
cd
which exit status: 1command -v name prints how the shell would resolve the name and exits non-zero when it cannot. It is specified in POSIX, runs inside the shell, and knows about builtins, functions and aliases. which is a separate program whose output and exit status differ between systems, and it cannot see a builtin, as the last two lines show.
command -v answers whether the shell can run the name, not whether it is the tool you expect. A function named git makes it succeed, so check the path with command -v git when that matters.