which
Overview
The which
command locates executable files in the system PATH. It shows the full path of commands that would be executed when typed in the shell.
Syntax
which [options] command...
Common Options
Option | Description |
---|---|
-a |
Show all matches in PATH |
-s |
Silent mode (exit status only) |
--version |
Show version |
--help |
Show help |
Key Use Cases
- Find executable locations
- Verify command availability
- Check PATH configuration
- Troubleshoot command issues
- Script validation
Examples with Explanations
Example 1: Find Command Location
which python
Shows the path to the python executable
Example 2: Multiple Commands
which python java gcc
Shows paths for multiple commands
Example 3: All Matches
which -a python
Shows all python executables in PATH
Understanding Output
- Returns full path if found
- No output if command not found
- Exit status 0 if found, 1 if not found
- Searches PATH directories in order
Common Usage Patterns
Check if command exists:
which git > /dev/null && echo "Git is installed"
Find all versions:
which -a python
Script validation:
command -v python || echo "Python not found"
PATH Environment
The which
command searches directories in the PATH environment variable:
echo $PATH
PATH order matters: - First match is returned - Earlier directories take precedence - Use -a
to see all matches
Performance Analysis
- Very fast operation
- No filesystem scanning
- Only searches PATH directories
- Minimal resource usage
- Efficient for scripting
Additional Resources
Best Practices
- Use in scripts to check dependencies
- Combine with conditional statements
- Use
command -v
for portability - Check exit status for automation
- Use
-a
to see all available versions
Alternative Commands
command -v
(POSIX standard):command -v python
type
command:type python
hash
for cached locations:hash python
Scripting Examples
Dependency check:
for cmd in git python make; do which "$cmd" > /dev/null || echo "$cmd not found" done
Version selection:
PYTHON=$(which python3 || which python)
Conditional execution:
which docker > /dev/null && docker --version
Troubleshooting
- Command not found in PATH
- Permission issues
- Symlink resolution
- Shell built-ins not shown
- Alias interference
Shell Built-ins
Note: which
doesn’t find shell built-ins like: - cd
- echo
(in some shells) - pwd
- history
Use type
to identify built-ins:
type cd
Integration Examples
With if statements:
if which node > /dev/null; then node --version fi
With variables:
EDITOR=$(which vim || which nano || which vi)
Error handling:
which python3 || { echo "Python3 required"; exit 1; }