An Introduction to the Command-Line (on Unix-like systems)
by Oliver; 20147. Where Are You? - Your Path and How to Navigate through the Filesystem
When you open up the terminal to browse through your filesystem, run a program, or do anything, you're always somewhere. Where? You start out in the designated home directory when you open up the terminal. The home directory's path is preset by a global variable called HOME. Again, it's /Users/username on a Mac.As we navigate through the filesystem, there are some conventions. The current working directory (cwd)—whatever directory we happen to be in at the moment—is specified by a dot:
.
Sometimes it's convenient to write this as:
./
which is not to be confused with the root directory:
/
When a program is run in the cwd, you often see the syntax:
$ ./myprogramwhich emphasizes that you're executing a program from the current directory. The directory one above the cwd is specified by two dots:
..
With the trailing slash syntax, that's:
../
A tilde is shorthand for the home directory:
~
or:
~/
To see where we are, we can print working directory:
$ pwdTo move around, we can change directory:
$ cd /some/pathBy convention, if we leave off the argument and just type:
$ cdwe will go home. To make directory—i.e., create a new folder—we use:
$ mkdirAs an example, suppose we're in our home directory, /Users/username, and want to get one back to /Users. We can do this two ways:
$ cd /Usersor:
$ cd ..This illustrates the difference between an absolute path and a relative path. In the former case, we specify the complete address, while in the later we give the address with respect to our cwd. We could even accomplish this with:
$ cd /Users/username/..or maniacally seesawing back and forth:
$ cd /Users/username/../username/..if our primary goal were obfuscation. This distinction between the two ways to specify a path may seem pedantic, but it's not. Many scripting errors are caused by programs expecting an absolute path and receiving a relative one instead or vice versa. Use relative paths if you can because they're more portable: if the whole directory structure gets moved, they'll still work.
Let's mess around. We know cd with no arguments takes us home, so try the following experiment:
$ echo $HOME # print the variable HOME /Users/username $ cd # cd is equivalent to cd $HOME $ pwd # print working directory shows us where we are /Users/username
$ unset HOME # unset HOME erases its value $ echo $HOME $ cd /some/path # cd into /some/path $ cd # take us HOME? $ pwd /some/pathWhat happened? We stayed in /some/path rather than returning to /Users/username. The point? There's nothing magical about home—it's merely set by the variable HOME. More about variables soon!