In Bash, when to alias, when to script, and when to write a function is as trivial as important it is. Here is a look at the underlying implementation, the "why" behind the "what".
aliases and functions
- are stored in memory (once they are read).
- When invoked, they are read from memory and executed by the current shell.
Note that aliases and functions are grouped together for their similarities despite being functionally different.
scripts
- are stored in files. If the script is located in a
$PATHdirectory, many shells store a hash of its pathname to save time on future$PATHlookups. - When invoked, they are read from files (i.e. file I/O takes place), and executed by a subshell (i.e. a
fork()will occur), unless sourced directly.
What does this mean? Ideal candidates for functions and aliases are commands that are very frequently used and very short, i.e. the type of things that you want to keep in memory and execute in the current shell for speed (although most OS's will cache commonly used files in memory). Ideal candidates for scripts are very long sequences of commands that are very rarely used, i.e. the type of things you don't want or need to permanently take up memory. A good example is initialization command sequences that only run once.
This could be important for performance -- function is faster, since it doesn't fork() and exec(). In normal circumstances, the difference is trivial, but if you are debugging a system that is out of memory and is page-thrashing, it could make a big difference.
Also, if you want to modify your current shell environment, you should use a function. For example, a function could change the command lookup $PATH for the current shell, but a script cannot, because it operates on a fork/exec copy of $PATH.
With that said, these considerations probably will not make much of a difference on most modern systems with average memory space and disk speeds. However, if you are ever developing scripts for systems with more extreme requirements (like tiny amounts of RAM or uncommon permanent storage media types), it may be useful to keep them in mind. Also, the difference between scripts and functions might be noticeable if you execute them a very large number of times in a row, like iterating over a long file list or a bunch of lines in very long file. Chances are, the function / alias will run faster because it does not need to fork a process or read a disk file, although again, OS-level caching and other optimizations may reduce the differences somewhat.
PS: According to Bash Reference Manual
PS: According to Bash Reference Manual
"For almost every purpose, shell functions are preferred over aliases."