Shahin
Shahin

Reputation: 1316

Bash built-in "history" can be executed, but is not in $PATH

I know shell builtins are loaded into memory and thought I could find all builtins in /usr/bin or somewhere in echo $PATH. I was trying to find out how the history command works. My assumption was that it is reading from ~/bash_history. So I tried objdump -S $(which history)

which history
echo $?

1

This did not return the path of the command which makes me where the binary for history is located.

type -t which
builtin

I assume this means that it is loaded onto memory. So does a shell process load builtins that are stored outside of echo $PATH

Upvotes: 1

Views: 188

Answers (1)

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

A shell builtin is literally built into the shell executable itself. It is invoked by the shell not as a separate process, but simply as a regular function call within the shell process. So if you want to find its source code, you need to look in the source code of bash.

For many builtins, such as cd, the main reason for it being a builtin is that it modifies the state of the shell itself. It would be pointless to have cd be a separate process, as that process would only change its own current directory, not that of the shell process. In the case of history, the reason is presumably that ~/.bash_history is only written when the shell exits, so the command also needs access to the in-memory history of the current session, which is contained within the running bash process. For other builtins, such as echo, the reason is performance: the command is assumed to be so frequently used that we want to avoid spawning a new process every time it is invoked (but if you really do want a process, there is also /bin/echo, which may behave differently).

Upvotes: 3

Related Questions