How do you do a dry run of rm to see what files will be deleted?

I want to see what files will be deleted when performing an rm in linux. Most commands seem to have a dry run option to show just such information, but I can’t seem to find such an option for rm. Is this even possible?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Say you want to run:

rm -- *.txt

You can just run:

echo rm -- *.txt

or even just:

echo *.txt

to see what files rm would delete, because it’s the shell expanding the *.txt, not rm.

The only time this won’t help you is for rm -r.

If you want to remove files and directories recursively, then you could use find instead of rm -r, e.g.

find . -depth -name "*.txt" -print

then if it does what you want, change the -print to -delete:

find . -depth -name "*.txt" -delete

(-delete implies -depth, we’re still adding it as a reminder as recommended by the GNU find manual).

Method 2

You can say:

rm -i

to run it in interactive mode, so rm will prompt you to confirm whether each file should be deleted. You could just answer no to each file to see which ones would be affected.

Method 3

You can use ls to list all the files that will be removed by rm:

ls ../path/*.txt

If you need to list to view the files that will be deleted with a recursive rm, then use the -R flag with ls:

ls -R ../path/*.txt

Method 4

Just wanted to belatedly point out a handy solution that Joshua mentioned in the comments:

yes n | rm -i myFile1 myFile2 myFile3

This runs rm in interactive mode, which prompts a y/n response for each file it would delete, but via yes n it automatically declines this prompt for each file. The output isn’t super pretty, but is parseable with a little cleanup.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x