2.2 Current Directory and Paths
Prerequisites: First Contact with the Shell Estimated time: 8 minutes Practice environment: Bash/Zsh and common Unix commands You are ready to continue when: you can explain current directory, absolute path, relative path,
~and..
The previous commands left files untouched. If you now run touch note.txt, where will the file appear? Its location depends on the shell's current working directory. Check that location before changing files.
Current Location and Directory Entries
pwd
ls
ls -la2
3
pwdprints the current working directory.lslists non-hidden entries.ls -lashows detailed output, including entries that begin with..
Do not assume the output is /home/steven. Linux commonly uses /home/username, macOS typically uses /Users/username, and containerized or remote hosts may exhibit different layouts.
Practice Moving with Temporary Directories
workdir=$(mktemp -d)
mkdir -p "$workdir/project/src"
cd "$workdir"
pwd
cd project/src
pwd
cd ..
pwd
cd -
pwd2
3
4
5
6
7
8
9
10
Paths fall into two categories:
/tmp/examplestarting from the root directory/is an absolute path.project/srcstarting from the current directory is a relative path.
Special notations:
| Syntax | Meaning |
|---|---|
. | Current directory |
.. | Parent directory |
cd - | Return to the previous working directory |
cd | Return to the home directory |
~ | Shell-expanded shorthand for the home directory |
~ is not the current directory. It is also not a simple text substitution of $HOME:
printf '%s\n' ~
printf '%s\n' "$HOME"
printf '%s\n' '~'2
3
The third line prints ~ verbatim because the quotes prevent tilde expansion.
Completion and Filename Boundaries
Pressing Tab after the first few characters of an input path helps reduce typos. The way different shells display candidate options can vary slightly.
Linux file names are usually case-sensitive; macOS's default file system is often case-insensitive, but project and deployment environments may differ. Cross-platform repositories should avoid relying solely on case to distinguish between two files.
Before clearing the practice area, exit it first:
cd
printf 'remove after inspection: %s\n' "$workdir"
rm -r -- "$workdir"2
3
Here, mktemp -d creates the directory and its path variable is always quoted. In real-world work, you should still first verify the target using ls -ld -- "$workdir".