I have just started using Linux and I am curious how shell built-in commands such as cd
are defined.
Also, I'd appreciate if someone could explain how they are implemented and executed.
If you want to see how bash builtins are defined then you just need to look at Section 4 of The Bash Man Page.
If, however, you want to know how bash bultins are implemented, you'll need to look at the Bash source code because these commands are compiled into the bash executable.
One fast and easy way to see whether or not a command is a bash builtin is to use the help
command. Example, help cd
will show you how the bash builtin of 'cd' is defined. Similarly for help echo
.
The actual set of built-ins varies from shell to shell. There are:
You can find out whether the utility is built in using the type
command, which is supported by most shells (although its output is not standardized). An example from dash
:
$ type ls
ls is /bin/ls
$ type cd
cd is a shell builtin
$ type exit
exit is a special shell builtin
Re cd
utility, theoretically there's nothing preventing a shell implementer to implement it as external command. cd
cannot change the shell's current directory directly, but, for instance, cd
could communicate new directory to the shell process via a socket. But nobody does so because there's no point. Except very old shells (where there was not a notion of built-ins), where cd
used some dirty system hack to do its job.
How is cd
implemented inside the shell? The basic algorithm is described here. It can also do some work to support shell's extra features.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With