Ubuntu – Bash alias that calls a script versus defining the script as a function

bashscripts

I have 150+ shortcuts defined in my .bash_aliases file. Some of them are simple commands, for example:

# Opens file with default program
o () { xdg-open "$@" & disown; }

# Folder shortcuts
alias ..='cd .. && ls'

Others are calling a script that I have somewhere else on the machine, such as:

alias i3exit='~/.config/i3/i3exit.sh'

And others are larger scripts defined like the o command above, only with 30-80 lines.

What is the difference between a script defined directly as a bash function, and an alias that calls a script from a different file? Is one preferable over the other, and if so, why?

Intuition tells me that having separate script files would be better but I don't have any arguments for that.

Best Answer

If you define these in your ~/.bash_aliases file, which is an Ubuntu-specific thing and gets sourced by ~/.bashrc in a default Ubuntu install, then yes, there is an overhead since the file will be sourced each time you start a new interactive, non-login shell. So each time you open a new terminal window, for example. Now, with modern machines, this overhead will most likely be undetectable, but it can be an issue for older machines, embedded systems or if you start having loads of complex functions defined.

In addition, functions and aliases defined this way are not accessible to scripts by default. So if you want to use one of those functions in your scripts, you will need to source .bashrc (or .bash_aliases) explicitly. If you have them as external script files in your $PATH, that won't be needed.

My personal rule of thumb comes down to the complexity of the commands involved and whether or not the function/script I am writing is likely to be useful to non-interactive shells (e.g. other scripts). If I find myself writing several dozen lines of code, then I'll likely move it to a script. If I'm writing something that can be used in many different contexts and can likely come in handy when writing another script then, again, I'll move it to a script.

If, however, I just want a simple little function like the one you show in your question, that's only really useful when run interactively, then I'll stick to functions. So it really is a matter of your own personal preference and considering how and when you will want to use the functions you are defining.

Related Question