Where are shell functions stored on Linux?

Solution 1:

User defined functions

Typically bash functions are permanently stored in a bash start-up script.

  • System-wide start-up scripts: /etc/profile for login shells, and /etc/bashrc for interactive shells.
  • User define start-up scripts: ~/.bash_profile for login shells, and ~/.bashrc for interactive shells.
  • More information on interactive/login shells can be found in the bash man page in the INVOCATION section.

User defined shell functions are loaded dynamically in a hash (or lookup table) when bash starts. From the bash source file variable.c the definition for the table is:

/* The list of shell functions that the user has created, or that came from
   the environment. */
HASH_TABLE *shell_functions = (HASH_TABLE *)NULL;

User defined functions can be listed with the bash declare command, other shells still use typeset. In bash declare has superceded the typeset command.

declare -f

The functions exist in memory for the lifetime of the bash shell.

Shell defined (builtin) functions

These are common functions such as echo, printf, cd and :. They are compiled into a library which is linked into the bash executable. Building the definitions into the executable saves time compared to loading an external definition. Definitions for these functions (held in .def source files which are parsed into C source) are held in the builtins directory of bash source.

A useful aside: for information on a shell builtin command use help <command>. e.g.

help                # list all builtins
help declare        # info and options for declare
help -m declare     # gives man style information for declare

Solution 2:

Shell functions are stored in the memory of the shell (or, perhaps, in undocumented temporary files).  They don't exist in any usable way until the shell starts (e.g., when you login to a CLI, or start a shell window such as xterm) and they are defined (e.g., by reading .bashrc, .bash_profile, or something similar) and they cease to exist when the shell terminates.

Solution 3:

cd and other common commands like echo, type & alias are so called builtins .

Builtin commands are contained within the shell itself and different shells may have different built in commands.

Solution 4:

The Super User question Finding the definition of a bash function is closely related to this one.  User HairOfTheDog provided this answer (paraphrased):

The following commands will report the location (filename and line number) of a function’s definition.  Assuming a function named foo,

# Turn on extended shell debugging
shopt -s extdebug

# Display the function’s name, line number and fully qualified source file
declare -F foo

# Turn off extended shell debugging
shopt -u extdebug

For example, the output of these commands might be:

foo 32 /source/private/main/developer/cue.pub.sh

The above might work only in bash, and not in POSIX shells in general.

Thanks to Blue Raspberry for finding this!