How to add a function to .bash_profile/.profile/bashrc in shell?

From man bash:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable.

In other words, you can put it in any one of ~/.bash_profile, ~/.bash_login or ~/.profile, or any files sourced by either of those. Typically ~/.profile will source ~/.bashrc, which is the "personal initialization file, executed for login shells."

To enable it, either start a new shell, run exec $SHELL or run source ~/.bashrc.


After you define the function in your .profile, add export -f date1. This will export the function for use by your login shell.


Customizations for interactive shells go into ~/.bashrc. Things that you want to run when you log in go into ~/.profile (or ~/.bash_profile, but it's often not loaded when logging in graphically).

Put this function definition in ~/.bashrc.

Since bash doesn't load .bashrc when it's a login shell, force it to do so: write a ~/.bash_profile containing

. ~/.profile
case $- in *i*) . ~/.bashrc;; esac

i.e. load ~/.profile, and also load ~/.bashrc if the shell is interactive.

See Alternative to .bashrc and the posts linked there.