bashrm

How to use rm interactively in a while read loop?


I'm little stuck in a script that's used to find and delete certain files. I want to give the user the opportunity to iterate through the list and delete each file only after human approval.

However, I find the script to skip the user interaction and don't delete.

cat $fileToBeDeleted | while read in; do

    rm -i "$in"
    echo "deleted: $in"

done;

Solution

  • Instead of using rm -i you can use if statement to ask for confirmation before you delete the file. In this example I used a text file (to_delete_list.txt) that contains the list of files that I will be deleting.

    read -u 1 answer will let you ask for user input in the loop.

    #!/bin/bash
    while IFS= read -r file; do
      echo "do you want to delete $file (y/n)?"
      read -u 1 answer
      if [[ $answer = y ]]
      then
            rm $file
            echo "deleted: $file"
      else
            continue
      fi
    done < "to_delete_list.txt"