alias vs. function in bash scripts

Think of aliases as nicknames. You might have a command that you perform a lot but want to shorten.

As an example, you often want to go straight to desktop in commandline, so you can do this

alias desktop="cd ~/Desktop"

From then on you just type

desktop

in terminal and it will perform the cd ~/Desktop for you.

Functions contains logic. In a function, you might make calls to several different programs. Here's a simple echo function

function e {
                echo $1 
                echo $1 $1
                echo $1 $1 $1                 
           }  

While it may appear similar to an alias when you call it

e Hello

Your e() can have a lot of different things happen. The above is a simplistic example.

Aliases should be reserved for simple use cases. Personal example - I have replaced my rm command like this

alias rm='trash-put'

Whenever I do an rm, it will send it to trash instead of deleting it from disk. This caters to my clumsiness in the terminal where I may (sometimes) accidentally delete an important file.

Functions, you need to remember, are pieces of logic. You wouldn't use a function standalone, usually. It would be part of a larger script. Imagine a script which takes all of your files and renames them to their pig latin versions. Ignore that there are different ways of doing it.

But what you could do is loop through every file in the directory and pass the filepath to your RenameAsPigLatin function. The RenameAsPigLatin function might have extra logic in there involving numbers, where you decide that files ending with numbers shouldn't be renamed.

Immediately you can see the benefit of having it as a function. The function can focus on the renaming by your strange rules while the rest of the script can traverse various directories as necessary.


An alias is a simple shortcut used in a console to avoid typing long commands or always repeating the same options.

A classical example would be:

alias ll='ls -l'

By default, aliases are only intended work in an interactive console. They are not meant to be used in scripts, though if you needed to do that, you could add shopt -s expand_aliases to scripts to enable alias expansion.

Functions can be used in scripts or in the console, but are more often used in scripts.

Contrary to aliases, which are just replaced by their value, a function will be interpreted by the bash shell.

Functions are much more powerful than aliases. They can be used to build very complex programs.

Tags:

Bash