02 Directories and Paths

Learning objectives

  • Determine the current directory.
  • List a directory’s contents and change directories.
  • Understand absolute paths, relative paths, a home directory, and a parent directory.

Command overview

CommandPurposeMeaningBasic usageExample
pwdShow the current directoryPrint working directorypwdpwd
lsList files and directoriesList directory contentsls [options] [path]ls -lah
cdChange directoriesChange the current directorycd pathcd /var/log
treeShow a directory treeDisplays contents hierarchicallytree [path]tree .
dirnameGet a path’s directory partRemoves the final file or directory componentdirname pathdirname /tmp/a.txt
basenameGet a path’s file-name partReturns the last path componentbasename pathbasename /tmp/a.txt
realpathNormalize and resolve a pathOutputs a canonical absolute path on GNU/Linuxrealpath [options] pathrealpath -e -- .
readlinkRead a symbolic linkShows a link target; options vary by implementationreadlink pathreadlink /proc/self/exe

Common scenarios

Show the current location and files:

pwd
ls -lah -- .

Change to common directories:

cd ~
cd ..
cd /var/log
cd -

Show directory hierarchy:

tree .
tree -L 2 .

Split and resolve paths:

dirname /home/user/project/app.py
basename /home/user/project/app.py
realpath -e -- .

Notes for beginners

  • A path beginning with / is absolute, for example /home/user.
  • A path not beginning with / is relative, for example ./data or ../logs.
  • ~ is the current user’s home directory.
  • . is the current directory and .. is the parent directory.
  • ls -lah is common: -l shows details, -a includes hidden files, and -h uses readable sizes.
  • Some systems do not install tree by default; use ls first when it is absent.
  • The path shown by a symbolic link can differ from its final object. Resolve and verify an absolute path before writes, deletion, or recursive operations.
  • In WSL, /mnt/c/... points to the Windows filesystem; permissions, case behavior, and I/O performance can differ from a Linux home directory.
  • Quote variables and paths with spaces, for example cd -- "$HOME/My Project".

Temporary-directory exercise

First use the safe lab environment to create a unique directory, then run:

path_lab=$(mktemp -d "$lab_real/path-lab.XXXXXX") || exit 1
mkdir -- "$path_lab/real dir"
ln -s -- "$path_lab/real dir" "$path_lab/link dir"
cd -- "$path_lab/link dir"
printf 'logical=%s\n' "$PWD"
printf 'physical=%s\n' "$(pwd -P)"
realpath -e -- .
cd -- "$lab_real"

Explain the difference among a logical path, physical path, and symbolic-link resolution. Inspect the target text stored in the link with readlink -- "$path_lab/link dir". $lab_real comes from the introduction; do not assume it still exists in a newly opened Shell. Keep the lab directory for manual inspection; do not remove it recursively automatically.

References