Wednesday, June 12, 2013

Add directory ~bin to PATH Ubuntu

Create a new directory in your PATH in Ubuntu with terminal

What is $PATH


$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.

What is bin

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.


$ 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  ...


Create Private bin directory

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


Create ~/bin directory

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.


$ 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  ...


One thing to watch out for when using which is that it will only find commands that are binaries in the filesystem, it does not report shell builtin, aliases, or functions. Often, it's more useful to use type to see how an actual command will be resolved by the shell; e.g.: which echo and type echo will report different things, which returns '/bin/echo' but 'type' returns that it's a shell builtin, which the shell will prefer over the file in '/bin'.

"Which" is better replaced by type or command in interactive shells, and it's completely useless in scripts.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...