Skip to content
shellhacks.dev
Shell Scripting

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.

1 min read
Summarize in AI

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.

Shell
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: $?"
Text
git: found
nosuchtool: missing
cd
which exit status: 1

command -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.

Share

More snippets

Shell Scripting

Test for a prefix without double brackets

Test for a prefix in POSIX sh with a case pattern such as release-*), which works in dash and every other shell where double brackets are a syntax error.

1 min read
Shell Scripting

Replace an array with positional parameters

POSIX sh has no arrays, but set -- a b c turns the positional parameters into one, and "$@" expands each element as its own word without splitting.

1 min read
Shell Scripting

Get a substring in POSIX sh

POSIX sh has no ${v:2:3}. Build a substring from two prefix strips instead, or use cut when a subprocess is acceptable. Both run in dash.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.