Appendix C. Loadable Built-Ins
bash 2.0 introduces a new feature that increases the flexibility of the shell: dynamically loadable built-ins. On systems that support dynamic loading, you can write your own built-ins in C, compile them into shared objects, and load them at any time from within the shell with the enable built-in (see Chapter 7, for details on all of the enable options).
This appendix will discuss briefly how to go about writing a built-in and loading it in bash. The discussion assumes that you have experience with writing C programs, compiling, and linking them.
The bash archive contains a number of pre-written built-ins in the directory examples/loadables/. You can build them by uncommenting the lines in the file Makefile that are relevent to your system, and typing make. We’ll take one of these built-ins, tty, and use it as a “case study” for built-ins in general.
tty will mimic the standard UNIX command tty. It will print the name of the terminal that is connected to standard input. The built-in will, like the command, return true if the device is a TTY and false if it isn’t. In addition, it will take an option, -s, which specifies that it should work silently, i.e., print nothing and just return a result.
The C code for a built-in can be divided into three distinct sections: the code that implements the functionality of the built-in, a help text message definition, and a structure describing the built-in so that bash can access it.
The description structure ...
Get Learning the bash Shell, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.