【问题标题】:Remove Files Based on Users Input - Bash Scripting根据用户输入删除文件 - Bash 脚本
【发布时间】:2015-07-06 12:53:31
【问题描述】:

我希望能够根据用户的输入删除文件。我有一个文件和目录列表,编号如下所示。我希望用户能够选择任何数字来删除相应的文件。例如,如果用户输入 2,DirectoryA 将被删除(假设他们有权限)。基本上,我想将用户输入的数字与文件匹配并删除文件。

这是我的代码显示的内容:

1. Directory1
2. DirectoryA
3. DirectoryB
4. Directory_C
---
5. File1
6. FileA
7. FileB
8. File_C
Please enter index of a file or directory to remove:

这是我的代码:

#!/bin/bash
if  [[ $# -ge 1 ]]; then
   cd "$1" 2> /dev/null
   if [[ $? = 1 ]]; then
      echo "Please enter a valid directory."
   else
         Dir="TRUE"

         i=0
         c=( $(ls --group-directories-first $*) )
         count=0;

         for f in ${c[@]}; do
            if [[ ${Dir} == "TRUE" && ! -d ${f} ]]; then
               echo ---
               Dir="FALSE"
            fi
         echo "$((++count)). $f";
         done
   fi
   echo "Please enter index of a file to remove: "
   read input
else
    Dir="TRUE"

         i=0
         c=( $(ls --group-directories-first $*) )
        count=0;

         for f in ${c[@]}; do
            if [[ ${Dir} == "TRUE" && ! -d ${f} ]]; then
echo ---
               Dir="FALSE"
            fi
         echo "$((++count)). $f";
         done
   fi
   echo "Please enter index of a file to remove: "
   read input

【问题讨论】:

  • 使用内置的select。这就是它的用途。
  • 你已经陈述了你想要什么,并展示了你编写的一些代码......但是问题是什么?
  • 我不得不评论cd "$1" 2> /dev/null; if [[ $? = 1 ]]; then echo "useless error message"的荒谬通过将cd的错误重定向到/dev/null,你正在扔掉一个有用的错误消息并用一个无用的错误消息替换它!

标签: arrays bash shell unix scripting


【解决方案1】:

试试这个代码。在每种情况下添加必要的操作以删除目录和文件。

read NUM
case $NUM in
1) echo "Removing directory1 (Add remove operations here instead of echo)" ;;
2) echo "Removing directoryA (Add remove operations here instead of echo)" ;;
#...
8) echo "Removing fileC (Add remove operations here instead of echo)" ;;
*) echo "Invalid index number!" ;;
esac

【讨论】:

    【解决方案2】:

    您可以使用内置的 bash select 来简化代码(正如 Etan Reisner 已经提到的)。这是一个例子:

    S3="Choose file or directory to delete: "
    
    select FILENAME in *;
    do
            rm -rf $FILENAME
            exit 0
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-22
      • 1970-01-01
      • 2017-02-28
      • 2021-01-17
      相关资源
      最近更新 更多