Bash Aliases, Functions and Commands
The first thing you type on a command-line is either an alias, a function or a command. If you haven’t written it yourself, it might not be obvious what exactly you’re calling.
If you’re curious about ;
in the function definition, read One-liner Bash Functions.
They all do the same thing, but you can’t tell what they are:
How can you tell? Use type -a:
So what?
It becomes important if you chain them. Worst case: an alias for a function that calls a command … all with the same name:
The order returned by type -a
is the evaluation order:
- aliases
- functions
- commands
Why would you do that?
The ls
command is often aliased. (… is ls
a command or builtin? type -a ls
).
Or you might do fancy things with cd
.
The point is that you can and it’s sometimes useful.
When to use which?
It’s complicated. Some guidelines:
aliases
For trivial things, when arguments (if any) come at the end.
functions
For more complicated things:
- positional arguments
- multi-line
- all the Bash you want
- “faster” – stored in the shell’s memory
- can modify current shell – you can’t implement
cd
as a command
commands
For everything else:
- don’t have to use Bash
- easily installed / shared – put somewhere in PATH
- can be used by other programs, subshells…