How to Enable Verbose Output for Bash Find Command with Execution Logging


2 views



When running potentially destructive operations like find with -exec rm -rf, it's crucial to have visibility into what's being processed. The standard find command operates silently, which can be dangerous when removing files.



The most straightforward approach is to add -print before the -exec action:

find /media/1Tb/videos -maxdepth 1 -type d -mtime +7 -print -exec rm -rf {} \;

This will output each directory path before executing the removal command.



For more detailed output, use -printf with custom formatting:

find /media/1Tb/videos -maxdepth 1 -type d -mtime +7 -printf "Found %p, executing rm -rf %p\n" -exec rm -rf {} \;



When performing batch operations, it's wise to maintain logs:

find /media/1Tb/videos -maxdepth 1 -type d -mtime +7 -printf "[$(date)] Processing %p\n" -exec rm -rf {} \; 2>&1 | tee find_cleanup.log



Always test first with a dry run:

find /media/1Tb/videos -maxdepth 1 -type d -mtime +7 -exec echo "Would remove {}" \;



For those preferring xargs:

find /media/1Tb/videos -maxdepth 1 -type d -mtime +7 -print0 | xargs -0 -I {} sh -c 'echo "Removing {}"; rm -rf {}'



GNU find offers built-in debugging:

find -D exec /media/1Tb/videos -maxdepth 1 -type d -mtime +7 -exec rm -rf {} \;

This shows how commands would be executed without actually running them.

When running complex find commands with destructive operations like rm -rf, having visibility into what's being processed is crucial for debugging and verification. Standard find output doesn't show the actual execution flow, which can be dangerous when deleting files.

GNU findutils 4.9.0+ introduced the -D debug option:


find /path -type f -delete -D tree

This shows the decision tree but doesn't print the actual commands executed.

Method 1: Using -print Before -exec


find /media/1Tb/videos -maxdepth 1 -type d -mtime +7 \
  -print \
  -exec echo "Executing rm -rf {}" \; \
  -exec rm -rf {} \;

Method 2: Wrapping in a Shell Function


verbose_find() {
  find "$@" -exec sh -c '
    echo "Processing: $1"
    exec "$@"
  ' find-sh {} "$@" \;
}

verbose_find /path -name "*.tmp" -delete

Method 3: Using xargs with Verbose Flag


find /path -type f -print0 | xargs -0 -t rm -v

For complex operations, consider this pattern that logs to a file:


{
  echo "=== Find operation started $(date) ==="
  find /target/path -type f -mtime +30 \
    -printf "Found: %p\n" \
    -exec sh -c 'echo "Deleting: $1"; rm -v "$1"' sh {} \;
} > find_operation.log 2>&1
  • Always test with -print first before adding destructive operations
  • Consider using -ok instead of -exec for interactive confirmation
  • For production scripts, implement dry-run modes with echo simulation