Appendix C. Loadable Built-Ins

bash 2.0 introduced a new feature that increased 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, compiling, and linking C programs.

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 relevant 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 is quite ...

Get Learning the bash Shell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.