Where can I put a user-defined shell function?

I am planning to create a function that would simplify things for me. The function would be something like

function lazymode()
{
echo "Hello World!";
}

so that when I use the command lazymode in the shell , it will output the Hello World!.

What file should I put the user-defined function?


Solution 1:

Depends on the function. If it's just a super-simple one-liner like that you could create an alias or stick the function in ~/.bashrc (a file that bash loads when it starts).

If you're creating something a bit more meaty, it might make more sense to create its own executable script in ~/bin/ which won't exist by default (it's just a directory) but should be in your path. Remember for this the file will need to be executable (chmod +x filename) and start with a proper #!/bin/bash stanza.

The second route has some clear benefits:

  • It's easier to see what's available
  • A syntax error won't tank your profile
  • You don't need to keep re-sourcing your bash config if you change the script
  • It's available to any shell as long as the full path is used or ~/bin/ is in the path for that shell too (which it should be in most cases AFAIK).

Solution 2:

The best choice would be ~/.bashrc file.

You can either write your shell function definitions directly in your ~/.bashrc file, or, if you have lots of them and don't want to clutter your ~/.bashrc file, you can put them all in another file of your choosing -- just be sure to source that file in your ~/.bashrc file. For example, if the file with your functions is named bash_functions, simply add in your ~/.bashrc file the lines:

if [[ -f /path/to/bash_functions ]]; then
    source /path/to/bash_functions
fi

or, equivalently:

if [[ -f /path/to/bash_functions ]]; then
    . /path/to/bash_functions
fi

where the . is just a symbolic representation of source. The if test makes sure the file /path/to/bash_functions exists before trying to source it.

This technique is very similar to establishing aliases in ~/.bashrc by creating a file called ~/.bash_aliases and using similar syntax to that above in ~/.bashrc to test for its existence and then source it.