What happens when you type a command name? How does Bash decide what to run?
AdvancedConceptShells, scripts and execution
Answer
Lookup order: aliases (interactive only by default), shell keywords (if, [[), functions, builtins (cd, echo, read), then a search of PATH directories left to right, cached in a hash table. For an external program Bash forks, sets up redirections in the child, and calls execve().
type -a echo # echo is a shell builtin / echo is /usr/bin/echo
command -v kubectl # path or nothing, exit 1 if missing
hash -r # forget cached paths after moving a binary
command -v is the portable way to check whether a tool exists.
More on Shells, scripts and execution
What is a shell, and how is Bash different from sh, dash and zsh?BeginnerWhat does the shebang line do, and why prefer `#!/usr/bin/env bash` over `#!/bin/bash`?BeginnerWhat is the difference between `./script.sh`, `bash script.sh` and `source script.sh`?BeginnerWhy must `cd`, `export` and `read` be builtins rather than external programs?IntermediateWhat is the difference between a login, interactive and non-interactive shell, and which startup files run?IntermediateWhat does `exec` do in a script? Give two uses.Advanced