Safely removing year-old files with confirmation (Unix find): Which command removes files (with a user confirmation prompt for each) that have neither been accessed nor modified in the last 365 days under /usr/?

Difficulty: Medium

Correct Answer: find /usr/ \( -mtime +365 -a -atime +365 \) -ok rm {} \;

Explanation:


Introduction / Context:
Cleaning up stale files on Unix must be done carefully. The find command can select files by access and modification times, while -ok executes a command with an interactive confirmation before each deletion, reducing the risk of accidental data loss.



Given Data / Assumptions:

  • Target directory tree: /usr/* (all first-level entries under /usr).
  • Staleness criteria: not accessed for >= 365 days and not modified for >= 365 days.
  • Safety requirement: prompt before deleting each file.
  • We want a single pipeline-free command using find's built-in primitives.


Concept / Approach:

find supports primary tests for modification time (mtime) and access time (atime), both expressed in days. Parentheses group conditions; -a denotes logical AND. The -ok action runs the specified command prompting '<< ... >> ?' for each candidate. The {} placeholder expands to the found pathname, and commands end with '\;'.



Step-by-Step Solution:

Select the search roots: /usr/.Build the predicate: \( -mtime +365 -a -atime +365 \).Use a safe action: -ok rm {} \; to prompt before removal.Combine into a single command: find /usr/ \( -mtime +365 -a -atime +365 \) -ok rm {} \;


Verification / Alternative check:

First replace -ok with -print to audit matches: find /usr/* \( -mtime +365 -a -atime +365 \) -print. After verifying, switch to -ok rm {} \; for prompted deletions, or use -exec rm {} \; if non-interactive removal is acceptable.



Why Other Options Are Wrong:

  • find -mtime +365 | rm: Pipes a list of names into rm incorrectly; also lacks atime criteria and prompts.
  • grep (/usr/) -mtime +365 | -ok rm: Mixes grep with find semantics; invalid syntax.
  • find -name -mtime +365 / -ok rm: Malformed ordering and missing arguments.
  • None of the above: Incorrect because a correct, safe find command exists (option A).


Common Pitfalls:

Forgetting to escape parentheses in shells; omitting {} and \; in -ok/-exec; using only mtime when access time policy also matters; and running as root without first auditing with -print, which can be hazardous.



Final Answer:

find /usr/ \( -mtime +365 -a -atime +365 \) -ok rm {} \;

More Questions from Unix

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion