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 pythonShows the path to the python executable
Example 2: Multiple Commands
which python java gccShows paths for multiple commands
Example 3: All Matches
which -a pythonShows 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 pythonScript validation:
command -v python || echo "Python not found"
PATH Environment
The which command searches directories in the PATH environment variable:
echo $PATHPATH 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 -vfor portability - Check exit status for automation
- Use
-ato see all available versions
Alternative Commands
command -v(POSIX standard):command -v pythontypecommand:type pythonhashfor cached locations:hash python
Scripting Examples
Dependency check:
for cmd in git python make; do which "$cmd" > /dev/null || echo "$cmd not found" doneVersion 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 cdIntegration Examples
With if statements:
if which node > /dev/null; then node --version fiWith variables:
EDITOR=$(which vim || which nano || which vi)Error handling:
which python3 || { echo "Python3 required"; exit 1; }