Ubuntu – When to use a preceding slash in path names? (e.g. for the ‘cd’ command)

command linepaths

I am a novice user and I am trying to install Oracle Java. The process calls for me to access /usr/local/java, but here is the problem. I get as far as /usr/local, then this is the message I get:

leonard@leonard-MT6452:/usr/local$ dir
bin  etc  games  include  java  lib  man  sbin  share  src

leonard@leonard-MT6452:/usr/local$ cd /java/
bash: cd: /java/: No such file or directory

leonard@leonard-MT6452:/usr/local$ rm -r ~/java
rm: cannot remove ‘/home/leonard/java’: No such file or directory

Help?

Best Answer

There are two ways a path can be specified.

Absolute paths

Absolute paths always start with a /. This means the starting point of the path specification is fixed. No matter where your current location is, an absolute path will always point to the same location. The only exception is when you use a shell shortcut, such as ~, at the start, where the shell will replace ~ with what is usually the absolute path of your home directory. Even though it doesn't look like ~/bin starts with a /, when the shell presents its final form, it will have a leading /.

Relative paths

Relative paths never start with /. Their starting point is the current directory, so where you end up depends on where you start. They may start with any subdirectory. In addition:

  • You can use . and .. to refer to the current directory and the parent directory. You can also use these within absolute paths, just not at the start (/foo/../bar is the same as /bar, and both are absolute paths, but ../foo is not absolute).
  • You can use a setting (environment variable) called CDPATH (usually unset), specifically for the cd command. If you add a directory to CDPATH, then you can use a relative path (not starting with . or ..) to it from anywhere with cd.

To summarize:

  • cd /usr/local/java will always take you to the same spot, as does cd /usr/local/./java.
  • cd java will take you different places depending on where you are and what CDPATH contains. (Note that only cd should be affected by CDPATH - for other commands, ./java and java should mean the same thing.)
  • cd ./java will take you to the directory named java within the current directory.
  • cd ../java will take you to the directory named java within the parent directory.
  • cd ~/java will always take you to the directory named java in your home directory. In this case, the path is absolute, but because the shell expands the ~ before cd operates on it, different users will end up at different places.
Related Question