Bash – automatically load shell scripts from /usr/bin

bashshell-script

Is there a way to have bash automatically load shell scripts I create and place into /usr/bin?

Or is there a different place I should put custom shell scripts so that they are automatically loaded?

For example suppose I create a script called myscript with contents:

#!/bin/bash
alias e=echo

and make it executable (chmod a+x), and put it into usr/bin. I am not able to call e from the commandline (when I try, it says the command wasn't found).

What am I doing wrong?

Best Answer

The alias you have defined will only take effect once the alias command is actually called. Thus if you were to do this:

$ source myscript
$ e "Hello"

It should work. However, this is clearly not ideal since you want e to be available whenever you start bash. Luckily, bash provides a number of ways to automatically run commands when the shell is started. For the full details of how bash starts up, see the manual page. For our purposes, it is enough to know that ~/.bashrc (that is, a file named ".bashrc" in your home directory) is run as your shell starts up. One way to make your alias available at startup would be to add this line at the end of ~/.bashrc:

source myscript

However, if you were to do this for every alias you wanted, your /usr/bin folder would likely become a mess. And, if you are on a multi-user system, filling /usr/bin/ with scripts like this may cause other users problems as well. Thus, it is better to place your aliases right inside .bashrc and forgo the separate script all together. Since you are using Ubuntu, inside your .bashrc file you probably have something that looks like this:

if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases 
fi

This code looks for a file call .bash_aliases in your home directory and runs anything it finds in that file as well. If you have this, or if you add this code to your .bashrc, you could also put your alias in ~/.bash_aliases. This provides an easy way to keep all your aliases in one place and keep your .bashrc file uncluttered.

Related Question