Navigating and managing files

Linux · Essentials · 10 min

These dozen commands are what you type most on any Linux machine.

Paths are absolute when they start with / and relative to the current directory otherwise. . is the current directory, .. its parent and ~ your home. pwd prints where you are, cd dir moves, cd alone goes home and cd - returns to the previous directory.

ls lists a directory: -l long format (permissions, owner, size, date), -a includes hidden dotfiles, -h human-readable sizes, -t sorts by time. File names are case-sensitive, and extensions mean nothing to the system.

Managing files:

  • mkdir -p a/b/c creates nested directories, touch f creates an empty file,
  • cp src dst copies (-r for directories, -a to preserve permissions and times),
  • mv src dst moves or renames,
  • rm f deletes, rm -r dir deletes recursively, rmdir removes empty directories.

There is no trash can: rm is permanent. Use -i to be asked, double-check globs with ls first, and never run rm -rf with a variable that might be empty.

find searches a tree by name, type, size or age: find . -name '*.log' -mtime +7 lists logs older than a week; add -delete or -exec to act on them. tree (if installed) draws a directory tree.

Example

cd "$(mktemp -d)"
pwd                              # /tmp/tmp.Xyz
mkdir -p project/src/utils       # -p: create parents, no error if present
touch project/README.md
cp project/README.md project/README.bak
mv project/README.bak project/notes.md   # move = rename
ls -la project                   # long listing, hidden files included
cp -r project project-copy       # -r for directories
rm -r project-copy               # recursive delete: there is no undo
find . -name '*.md' | sort       # ./project/README.md ./project/notes.md
find . -type d -empty            # ./project/src/utils
cd project/src && cd ../..       # .. is the parent directory
cd - >/dev/null && pwd           # back to the previous directory

Remember

  • Absolute paths start with /; . is here, .. is the parent, ~ is home
  • cp -r and rm -r for directories; mv also renames
  • rm is permanent; find searches by name, type, size and age

Watch out for

  • Running rm -rf "$DIR"/* when DIR is empty, which expands to /*.

Check yourself

  1. What does `mv report.txt final.txt` do in the same directory?
  2. Which command lists files under the current directory with names ending in .log?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: man7.org/linux/man-pages/man1/ls.1.html