Skip to content

Instantly share code, notes, and snippets.

@snappytux
Last active May 23, 2025 03:27
Show Gist options
  • Save snappytux/8db73d52b17f53e59459b5814797a263 to your computer and use it in GitHub Desktop.
Save snappytux/8db73d52b17f53e59459b5814797a263 to your computer and use it in GitHub Desktop.
rm all files except some
#!/bin/bash
# File removal script - removes all files except specified exceptions
# Add safety checks and better error handling
set -e # Exit on any error
# Define files to keep (you can modify this list)
KEEP_FILES=(
"*ignore"
"bk.sh"
"rmFile.sh"
"*.log" # Example: keep log files
"config.*" # Example: keep config files
)
# Function to build find command with exclusions
build_find_command() {
local cmd="find . -type f"
for pattern in "${KEEP_FILES[@]}"; do
cmd="$cmd -not -name '$pattern'"
done
echo "$cmd"
}
# Safety check - prompt for confirmation
echo "This will remove all files in the current directory except:"
printf ' - %s\n' "${KEEP_FILES[@]}"
echo
read -p "Are you sure you want to continue? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Operation cancelled."
exit 0
fi
# Show what would be deleted (dry run)
echo "Files that will be deleted:"
eval "$(build_find_command)" | head -10
file_count=$(eval "$(build_find_command)" | wc -l)
echo "... and $((file_count - 10)) more files (total: $file_count files)"
echo
read -p "Proceed with deletion? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
# Perform the actual deletion
eval "$(build_find_command)" -print0 | xargs -0 rm -f
echo "Files removed successfully."
else
echo "Operation cancelled."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment