Ubuntu – put a user-defined shell function

bashcommand linefunctions

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?

Best Answer

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).