Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to $PATH vs using aliases: Which is better?

In at least some cases, aliases and adding $PATH locations can be used interchangeably. For example, looking at the python tool couchapp, I need to either alias the executable (as helpfully described here) or make the executable available via $PATH.

These are the two lines that can achieve this:

alias couchapp="~/Library/Python/2.7/bin/couchapp"

OR

export PATH=$PATH:~/Library/Python/2.7/bin/

Is there a very definite 'better' option of these two? Why or why not?

like image 698
Zach Smith Avatar asked Dec 15 '16 02:12

Zach Smith


1 Answers

  • An alias is a shell feature: any environment that invokes utilities directly, without involving a shell will not see aliases.

    • Note: Even when calling shell commands from languages such as Python (using, e.g., os.system()), user-specific shell initialization files are typically not called, so user-specific aliases still won't be visible.
  • A directory added to the $PATH environment variable is respected by any process that tries to invoke an executable by mere filename, whether via a shell or not.

    • Similarly, this assumes that any calling process sees the $PATH environment-variable additions of interest, so additions made by the user-specific initialization files are typically not seen, unless the calling process was launched from an interactive shell.

Lookup cost

If you know that a shell will be involved in invoking your utility, you can keep overhead down by defining aliases that invoke your executables by their full path.
Of course, you need to do this for each executable you want to be callable by name only.

By contrast, adding directories to the $PATH variable potentially increases the overhead of locating a given executable by mere filename, because all directories listed must be searched one by one until one containing an executable by the specified name is found (if any).

Precedence

If a shell is involved, aliases take precedence over $PATH lookups.
Of course, later alias definitions can override earlier ones.

If no shell is involved or no alias by a given name exists, $PATH lookups happen in the order in which the directories are listed in the variable.

like image 129
mklement0 Avatar answered Sep 22 '22 12:09

mklement0