Thursday, November 18, 2021

[SOLVED] How do you delete all hidden and non-hidden files except one in bash?

Issue

I have a question. How do you delete all hidden and non-hidden files except one in bash? BEcause I am creating a repository, and just now creating a update script.


Solution

This will delete everything in the current directory that you have permission to remove, recursively, preserving the file named by -path, and its parent path.

# remove all files bar one
find . -mindepth 1 -not -type d -not -path ./file/to/keep -exec rm -rf {} +

# then remove all empty directories
find . -mindepth 1 -type d -exec rmdir -p {} + 2>/dev/null

rmdir will get fed a lot of directories its already removed (causing error messages). rmdir -p is POSIX. This would not work without -p.

You can keep more files with additional -path arguments, and/or glob patterns. The paths must match the starting point, ie. ./.



Answered By - dan