Why must `cd`, `export` and `read` be builtins rather than external programs?
IntermediateConceptShells, scripts and execution
Answer
An external program runs in a child process, and a child cannot change its parent's state. If cd were /usr/bin/cd, it would change the child's directory and exit, leaving your shell where it was. The same applies to export (shell environment), read (sets shell variables), set, trap, exit and source. That is also why sudo cd /root fails: sudo can only exec programs.
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`?BeginnerWhat happens when you type a command name? How does Bash decide what to run?AdvancedWhat 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