Shell – How to Add a Function to .bash_profile/.profile/bashrc

bashfunctionprofileshell

I have a function which converts epoch time to date. Here is the definition

date1(){
  date -d @$1
}

I'd like to be able to write:

$ date1 xxxyyy

Where xxxyyy is the parameter I pass into my function so I can get the corresponding date. I understand I have to add it in either .bash_profile, .profile, or .bashrc and then source it:

$ source file

But, I'm not sure which file to put it in. Currently, I have it in .profile.
But to run it, I have to do source .profile every time.

Ideally, it should make it available, when the computer starts up like the environment variable.

Best Answer

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.

Related Question