Ubuntu – Should I create an alias for each bash function

aliasbash

I did a short course on bash and terminal and one of the best practices laid out in the course was creating an alias for each function to be created. For example if I had a function:

function e() { echo "$*"; }

I should also create create an alias:

alias e='e'

Do you think it makes sense and if yes what is the reasoning? I figure I can source the functions and use them without aliases anyway so it seems kind of like unnecessary work.

Best Answer

Case for aliases

  • Aliases can be quite useful when you want to refer to a lengthy command by a short name.
  • In the order of precedence, aliases stand higher than functions, so in case where you want to override some existing name for your own session you'd use an alias.

Case for functions

  • When you have a command that requires dealing with single and double quotes at the same time, use functions. Those who deal with sed or awk a lot understand.
  • When you want to refer to a lengthy task consisting of multiple commands interacting with variables, use function. In general , I personally follow the rule that if there's more than 3 commands, it's time to use a function.
  • Aliases can be escaped by appending \. This is useful for system administrators. If you don't want your user to run certain command, a function will take precedence over . Example:

    $ ls
    serg says this command is a no-no
    $ \ls
    serg says this command is a no-no
    

    note that user can still run /bin/ls with no problems there, so it's not really a good security measure. I'd say the better use would be as a wrapper for some command, where you want to add a header or remove some information.

  • From bash man page: There is no mechanism for using arguments in the replacement text.If arguments are needed, a shell function should be used. Thus while you can do simple tricks - something like alias e="echo"; e Hello - you would want a function when you want to deal with command-line arguments extensively.

In my personal experience, I found myself using functions far more than aliases. They are like scripts, except it's not necessary to create external files - they can all live in my ~/.bashrc. Quoting and referencing variables become less of a problem.