Linux commands
Browse topics

Locating commands with command -v, type and which

Version
unversioned
Review
Draft

Summary#

The shell finds a command among aliases, functions, builtins and the directories listed in PATH. command -v reports what a name resolves to.

Syntax#

sh
command -v python3
type -a python3
which python3
whereis ssh
echo "$PATH"

command -v is part of POSIX and suits scripts. type -a in Bash lists every match. which is a separate program that searches only PATH, and whereis also looks for manual pages.

Example#

sh
(
  set -eu
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT
  printf '#!/bin/sh\necho "hello from the tool"\n' > "$dir/dl-tool"
  chmod +x "$dir/dl-tool"

  command -v cd
  command -v dl-tool || echo 'dl-tool: not on PATH'
  PATH="$dir:$PATH"
  test "$(command -v dl-tool)" = "$dir/dl-tool" && echo 'dl-tool: found on PATH'
  dl-tool
)

Expected output#

Text
cd
dl-tool: not on PATH
dl-tool: found on PATH
hello from the tool

Common mistakes#

command not found means that no alias, function, builtin or PATH directory provides the name. Check the spelling, then whether the package is installed. Run a program in the current directory as ./name, and make sure it is executable. sudo, cron and services often use a shorter PATH than your interactive shell. After moving a program, Bash may remember its old location; run hash -r. which cannot see shell functions or builtins.

Version applicability#

This entry describes POSIX shells such as Bash and Dash. Messages and the output of type differ between shells.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0