簡體   English   中英

根據用戶輸入刪除文件-Bash腳本

[英]Remove Files Based on Users Input - Bash Scripting

我希望能夠根據用戶的輸入刪除文件。 我有一個文件和目錄的列表,編號如下所示。 我希望用戶能夠選擇任何數字以刪除相應的文件。 例如,如果用戶輸入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

試試這個代碼。 分別添加必要的操作以刪除目錄和文件。

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

您可以使用內置的bash select來簡化代碼(如Etan Reisner所述)。 這是一個例子:

S3="Choose file or directory to delete: "

select FILENAME in *;
do
        rm -rf $FILENAME
        exit 0
done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM