4.4 Useful Commands: Files, Search, Environment

Key Takeaways

  • cp needs -r to copy directories recursively, mv both moves and renames, and mkdir -p creates whole parent chains without errors
  • less is the preferred pager; head and tail -n control how many lines you see, and tail -f follows a growing log live
  • find walks the live filesystem (find / -name x -type f) while locate answers instantly from a database refreshed by updatedb
  • grep filters text with -i (case-insensitive), -r (recursive), -n (line numbers), -v (invert); which finds a command in PATH, whereis adds man pages and sources, and type resolves aliases and built-ins
  • tee writes output to a file and the screen at once (-a appends); df -h, du -sh, and free -h report disk and memory usage
Last updated: July 2026

Managing and Viewing Files

These are the commands you will type hundreds of times; the exam checks the options precisely.

  • ls lists directory contents: -l for the long format (permissions, owner, size, time), -a to include hidden dotfiles, -h for human-readable sizes, -t to sort by modification time.
  • cd changes directory; bare cd returns you home, cd - jumps back to the previous directory.
  • cp source dest copies files; copying a directory requires -r (recursive), and -p preserves timestamps and permissions.
  • mv both moves and renames — mv old.txt new.txt renames in place; no -r is needed for directories.
  • mkdir creates directories; -p builds the whole chain (mkdir -p engagement/scans/nmap) without complaining about existing parts.
  • rm deletes files; rm -r recurses into a directory tree and rm -f forces past prompts, while rmdir removes only an already-empty directory. rm -rf has no undo, so read the path twice before you press Enter.

For viewing, cat dumps whole files (fine for short ones; -n numbers lines), but less is the real pager: scroll with arrows and Page Up/Down, search with /pattern, jump to the end with G, quit with q. head shows the first 10 lines and tail the last 10 by default; -n 50 changes the count, and tail -f /var/log/auth.log follows a growing file live — essential when watching logs during a brute-force attempt.

Searching: find vs. locate, and grep

find searches the live filesystem and takes a starting path plus tests and actions:

find / -name report.pdf            # exact name
find /home -iname '*.txt'          # case-insensitive glob
find / -type f -size +100M         # files over 100 MB
find /etc -mtime -1                # modified in the last day

locate answers the same style of question almost instantly, but from a filename database, not the disk — so results can be stale or miss files created since the last refresh. Update the database with sudo updatedb before relying on it. Rule of thumb: locate for speed, find for accuracy and rich filters.

grep filters text, either files or piped input:

grep -i error /var/log/syslog      # case-insensitive
grep -rn 'password' /etc           # recursive, with line numbers
grep -v '^#' sshd_config           # invert: drop comment lines
ps aux | grep nmap                 # filter command output

Add -E for extended regular expressions (e.g. grep -E 'root|admin' file).

Environment, Identity, and Disk Usage

Three commands locate a program: which nmap prints the path your shell would execute by searching PATH; whereis nmap also lists man pages and source locations; type nmap is a shell built-in that reveals how the name resolves — alias, keyword, shell built-in, or external file (type cd reports a built-in). Inspect the environment with echo $PATH or dump it all with printenv; make a variable visible to child processes with export NAME=value.

For storage and memory triage: df -h shows free space per mounted filesystem, du -sh /var/log sums one directory's disk usage, and free -h reports RAM and swap. For system and hardware inventory: uname -a prints the kernel name, release, version and machine architecture; id shows your UID, GID and group memberships; dmesg dumps the kernel ring buffer and journalctl -u ssh.service queries the systemd journal (-r newest-first, -f to follow, -b for this boot); and lspci and lsusb enumerate PCI and USB devices — lsusb being the quickest way to confirm that a USB Wi-Fi adapter really reached a Kali guest. file mystery.bin identifies a file's real type by inspecting magic bytes rather than trusting the extension — indispensable when triaging captured payloads. Finally, tee splits a stream so output goes to both the screen and a file, the standard way to keep evidence while watching a scan: nmap -sV target | tee scan.txt overwrites, and tee -a appends.

Combining the Commands

These tools become powerful in combination, joined by the pipe operator | which feeds one command's standard output into the next command's standard input. A classic investigation chain is du -sh /var/* | sort -h | tail -n 5 to find the five largest directories under /var, or find / -name '*.log' | xargs grep -l 'Failed password' to search every log file for failed logins (xargs turns piped filenames into arguments for grep). When reading df -h, watch the Use% column for the filesystem mounted on / — a full root filesystem breaks updates and logging — while free -h answers a different question: the available column, not free, shows how much RAM applications can actually still claim, because Linux deliberately uses idle memory for disk cache. Knowing that distinction prevents misreading a healthy system as memory-starved, and it is exactly the kind of interpretation the exam probes.

Command Reference

CommandPurposeKey options / notes
lsList directory contents-l long, -a hidden, -h human sizes
cdChange directorybare = home, cd - = previous
cpCopy files/directories-r recursive (required for dirs), -p preserve attrs
mvMove or renameno -r needed for directories
mkdirCreate directories-p creates parent chain
cat / lessDump / page file contentsin less: / search, G end, q quit
head / tailFirst / last lines (10 default)-n N count, tail -f follow
findLive filesystem search-name, -iname, -type f, -size, -mtime
locateDatabase filename searchrefresh with sudo updatedb
grepFilter lines by pattern-i, -r, -n, -v, -E
which / whereis / typeLocate commands / resolve namestype unmasks aliases and built-ins
echo / printenv / exportInspect and share variablesexport for child processes
df / du / freeDisk and memory usageall take -h for human-readable
fileIdentify file type by contentignores the extension
teeWrite to file and stdout-a append instead of overwrite

Learn the table cold: KLCP questions often present a task ('follow a log file as it grows' → tail -f, 'copy a directory tree' → cp -r) and expect the exact command and flag.

Test Your Knowledge

You need to locate every file named id_rsa on a Kali machine that was heavily modified in the last five minutes, and the results must reflect the current state of the disk. Which approach fits, and why?

A
B
C
D
Test Your Knowledge

You are capturing live Nmap output and want it saved to a file for your report while still watching progress on screen. Which command does this?

A
B
C
D