When to use a preceding slash in path names? (e.g. for the 'cd' command)
Solution 1:
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 thecd
command. If you add a directory toCDPATH
, then you can use a relative path (not starting with.
or..
) to it from anywhere withcd
.
To summarize:
-
cd /usr/local/java
will always take you to the same spot, as doescd /usr/local/./java
. -
cd java
will take you different places depending on where you are and whatCDPATH
contains. (Note that onlycd
should be affected byCDPATH
- for other commands,./java
andjava
should mean the same thing.) -
cd ./java
will take you to the directory namedjava
within the current directory. -
cd ../java
will take you to the directory namedjava
within the parent directory. -
cd ~/java
will always take you to the directory namedjava
in your home directory. In this case, the path is absolute, but because the shell expands the~
beforecd
operates on it, different users will end up at different places.
Solution 2:
You don't need the initial /
while at /usr/local/
to go to /usr/local/java
. The correct command using relative pathname:
leonard@leonard-MT6452:/usr/local$ cd java/
leonard@leonard-MT6452:/usr/local/java$ pwd
/usr/local/java
You can also take help of bash_completion
by just typing cd j
(provided there is no other directory started with j
) and then hit Tab, cd java/
will be printed.
Additionally you can use the absolute path from anywhere:
cd /usr/local/java
The /
at the start of a file path always refers the root directory of the file system hierarchy. As there is no file named /java
you were getting /java/: No such file or directory
error message.