Reloading functions at shell startup

We can declare as many functions on the Bash interactive shell as we like, but just as functions are only visible during that bash session, they're not persistent either: as soon as the Bash shell in which they were declared exits, they disappear.

If you write a function on the command line that's convenient for you and that you'd like to be available in future sessions, you might want to arrange for that function to be loaded on startup. For most Bash configurations, a good place to put such function declarations is in your ~/.bashrc file. On many systems, such a file may already exist, provided for you with some starting configuration and aliases.

Fortunately, Bash makes it easy to save defined functions for later use; you can reproduce code that will declare them with the -f option of declare. Let's examine the output of this command when run with our home example function:

bash$ declare -f home
home ()
{
    printf '%s\n' "$HOME"
}

Note that the function doesn't resemble exactly how we declared it, which was all on one line; this is how bash has chosen to format it, but it still works the same way. We can save this into our ~/.bashrc file for later, using >> so that we append to the file's existing contents, rather than >, which would overwrite it:

bash$ declare -f home >> ~/.bashrc

If you examine the ~/.bashrc file in your favorite editor, you'll find that the function declaration is now at the end of it. If the .bashrc file is indeed being sourced on startup for interactive shells as normal, then the function will be available to you the next time you start an interactive bash session on the same host and as the same user.

If you change your ~/.bashrc file, you can also reload it without logging out by typing source .bashrc.