How to Create a Bash Script to Find and Delete Large Files Interactively

0
3
Asked By CuriousCoder123 On

Hey everyone! I'm looking for assistance with a bash script I'm trying to write. The goal is to find files larger than a specified size (in MB) starting from the current directory and to prompt the user for each found file, asking whether to delete it or skip it.

Here's the script I've come up with so far:

```bash
#!/bin/bash

if [ $# -ne 1 ]; then
echo "Usage: $0 "
exit 1
fi

size_in_mb=$1

find . -type f -size +"${size_in_mb}M" | while IFS= read -r file; do
size=$(du -h "$file" | cut -f1)
echo "File: $file"
echo "Size: $size"
while true; do
read -p "Do you want to delete this file? (y/n): " choice
case "$choice" in
[Yy]* )
rm "$file"
echo "Deleted: $file"
break
;;
[Nn]* )
echo "Skipped: $file"
break
;;
* )
echo "Please answer y or n."
;;
esac
done
done
```

When I run `./findlargefiles.sh 50`, I keep getting an infinite loop with the message "Please answer y or n." Any tips on how to resolve this issue? I'm testing this on an Ubuntu 22.04 server. Thanks a bunch!

5 Answers

Answered By ScriptSavvy99 On

Consider trying this simpler command: `find . -type f -size +"${size_in_mb}M" -exec rm -iv -- "{}" +`. This will ask for confirmation before deleting files and simplify your script significantly.

Answered By NerdyNina On

As others pointed out, your infinite loop seems to stem from not properly capturing the input for deletion interaction. Using `read choice < /dev/tty` is a good fix, as it ensures the prompt reads from the actual terminal instead of the pipeline.

Answered By WittyWhiz On

You might want to consider limiting the infinite loop, especially if it keeps prompting even with no valid responses. Maybe a counter could help to end the loop after a certain number of prompts, or simply include an option to exit if the response isn't valid.

Answered By HelpfulHarry88 On

The main problem with your script is that both `read` commands are pulling from the same input stream that's being fed by `find`. Instead of trying to use `while true; do` for the prompt, change the user input `read` to pull from the terminal specifically using `read -p "Do you want to delete this file? (y/n): " choice < /dev/tty`. This way, there's no mix-up between the file names from `find` and the user's input.

Answered By BashBuddha On

It's crucial to keep separation between your input streams. A better structure could be: `while read -u 3 line; do read -p "Do you want to delete this file $line? (y/n): " choice < /dev/tty; done 3< <(find . -type f -size +"${size_in_mb}M")`. This reads from `find` into a different file descriptor, avoiding confusion with user responses.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.