02 / FILES AND BACKUPS · LESSON 05

Inventory workspace files

Count file bytes safely and distinguish missing paths from empty files.

16 min · learn at your pace

Filenames are not words

A maintenance script often starts with a list of files to examine. A filename containing spaces, brackets or a percent sign is still one path. Use read -r with IFS cleared, quote every expansion, and supply a constant printf format. Parsing ls output or looping over command substitution breaks that boundary.

The manifest in this exercise is a trusted list of relative paths beneath the workspace. It excludes slashes leading outside the workspace, tabs and embedded newlines. A general filesystem walker would need a richer path contract; this lesson intentionally keeps enumeration separate from measurement.

Measure bytes, then describe state

wc -c counts bytes when given a file through input redirection. It does not count user-perceived characters. UTF-8 text can therefore have a larger byte count than character count, and an empty regular file has zero bytes while still existing.

Test -f identifies regular files. A missing path or a directory is not an empty file and gets a separate state. The report can then support a later retention or backup decision without manufacturing a zero-size observation. No file is removed or changed here. Required commands and options work on both the browser Linux guest and native macOS.

Try an example.sh
printf 'Byte count: '
wc -c < './data/notes.txt'
YOUR TURN

Put it into practice.

Read files.txt as trusted, nonempty relative workspace paths (no .. components, tabs or embedded newlines). Print path<TAB>bytes<TAB>state in manifest order. For regular files print their exact byte count and present; otherwise print - and not_file. Preserve spaces, Unicode and an unterminated final manifest entry. Do not change any source file.

See an explained solution
One way to solve it.sh
printf 'path\tbytes\tstate\n'
while IFS= read -r path || [ -n "$path" ]; do
 if [ -f "./$path" ]; then
  bytes=$(wc -c < "./$path") || exit 1
  printf '%s\t%d\tpresent\n' "$path" "$bytes"
 else printf '%s\t-\tnot_file\n' "$path"
 fi
done < files.txt

The regular-file test separates absence from a genuine zero-byte observation. Quoting preserves path boundaries, and numeric formatting removes platform-specific padding from wc’s count without changing the measured bytes.