首页 > 解决方案 > 如何在 while 读取循环中以交互方式使用 rm?

问题描述

我很少陷入用于查找和删除某些文件的脚本中。我想让用户有机会遍历列表并仅在人工批准后删除每个文件。

但是,我发现脚本跳过用户交互并且不删除。

cat $fileToBeDeleted | while read in; do

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

done;

标签: bashrm

解决方案


rm -i在删除文件之前,您可以使用 if 语句来请求确认,而不是使用。在此示例中,我使用了一个文本文件 (to_delete_list.txt),其中包含我将要删除的文件列表。

read -u 1 answer将让您在循环中要求用户输入。

#!/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"

推荐阅读