Shell – What exactly happens when a built-in command is run in a shell

shellshell-builtinthread

I know that external commands are run in the shell by creating a separate process, but what exactly happens when a built-in command is run in a shell?

Are they executed as a function, or does the shell create a new thread to execute them?

Best Answer

For your concrete example, there is a function cd_builtin, which is defined in builtins/cd.def (in the bash source code). It normally does a cd by calling that function. But it may fork first if you use it in a pipeline—for example, cd / | echo forks and calls cd_builtin in the child. You can also notice this by how the directory doesn't actually change:

anthony@Zia:~$ cd /tmp/
anthony@Zia:/tmp$ cd / | echo -n
anthony@Zia:/tmp$ cd /
anthony@Zia:/$ 

Notice how the directory only changes when I don't pipe from cd.