What are "$PATH" and "~/bin"? How can I have personal scripts?

Solution 1:

$PATH is an environment variable used to lookup commands. The ~ is your home directory, so ~/bin will be /home/user/bin; it is a normal directory.

When you run "ls" in a shell, for example, you actually run the /bin/ls program; the exact location may differ depending on your system configuration. This happens because /bin is in your $PATH.

To see the path and find where any particular command is located:

$ echo $PATH
/home/user/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:...
$ which ls     # searches $PATH for an executable named "ls"
/bin/ls
$ ls           # runs /bin/ls
bin  desktop  documents  downloads  examples.desktop  music  pictures  ...
$ /bin/ls      # can also run directly
bin  desktop  documents  downloads  examples.desktop  music  pictures  ...

To have your own private bin directory, you only need to add it to the path. Do this by editing ~/.profile (a hidden file) to include the below lines. If the lines are commented, you only have to uncomment them; if they are already there, you're all set!

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ]; then
  PATH="$HOME/bin:$PATH"
fi

Now you need to create your ~/bin directory and, because .profile is run on login and only adds ~/bin if it exists at that time, you need to login again to see the updated PATH.

Let's test it out:

$ ln -s $(which ls) ~/bin/my-ls   # symlink
$ which my-ls
/home/user/bin/my-ls
$ my-ls -l ~/bin/my-ls
lrwxrwxrwx 1 user user 7 2010-10-27 18:56 my-ls -> /bin/ls
$ my-ls          # lookup through $PATH
bin  desktop  documents  downloads  examples.desktop  music  pictures  ...
$ ~/bin/my-ls    # doesn't use $PATH to lookup
bin  desktop  documents  downloads  examples.desktop  music  pictures  ...

Solution 2:

Regarding ~/bin and commands/programs only available to your user

Recent Ubuntu versions include the ~/bin directory in your $PATH, but only if the ~/bin directory exists.

If it does not exist:

  1. Ensure that your ~/.profile contains the following stanza (the default ~/.profile already does):

    # set PATH so it includes user's private bin if it exists
    if [ -d "$HOME/bin" ] ; then
        PATH="$HOME/bin:$PATH"
    fi
    
  2. Create the ~/bin directory:

    mkdir -p ~/bin
    
  3. Either reboot your computer, or force bash to re-read ~/.profile:

    exec -l bash