簡體   English   中英

將空文件從當前目錄移動到子目錄

[英]Moving empty files from current directory into a sub directory

我正在嘗試制作一個 bash 腳本,該腳本將檢查當前目錄中是否存在子目錄“Empty_Files”,如果它不存在,它將創建子目錄。 然后它將檢查當前目錄中的所有常規非隱藏文件,如果文件為空,它將詢問您是否要移動該文件。 如果用戶說是,它會將文件移動到 Empty_Files 目錄中。 但是,當我運行腳本時,它只是說在當前目錄中找不到空文件,但仍然詢問我是否要移動文件。 不知道為什么要這樣做。 任何幫助都會受到歡迎。

   #!/bin/bash

#Script to move empty files from current directory into the sub directory Empty_Files

# usage:  ./move_empty


subdirectory="Empty_Files"


if [ -f $subdirectory ]  # does the Empty_Files file exist?
then
   echo $subdirectory "exists!"
else
   mkdir -p /home/student/Empty_Files
   echo "Empty_Files subdirectory created"
fi

currentfiles=$( ls . )  # check all non hidden files in current directory

for eachfile in $currentfiles
do
   checksize=$(du -sh $eachfile | awk '{print $1}')

   if [ "$checksize" = "0" ] # check if any files are empty
   then
      echo -n "Would you like to move the file Y/N:" # if a file is empty ask the user if the want to move the file
      read useranswer
   fi

   if [ "$useranswer" = "y" ] || [ "$useranswer" = "Y" ]
   then
      mv "$eachfile" /home/student/Empty_Files
      echo "mv command successful"
   elif [ "$useranswer" = "n" ] || [ "$useranswer" = "N" ]
   then
      echo "File will not be moved"
   fi

   if [ ! -z "$currentfiles" ]
   then
      echo "no empty files found in the current directory"
      #exit 55
   fi
done

你有幾個問題。

當文件不為空時,您可以跳過詢問用戶是否要移動文件的代碼,但您仍會執行移動文件的代碼。 它使用前一個文件中$useranswer的值,所以它會在移動一個空文件后移動所有非空文件,直到它到達下一個空文件。 執行移動的代碼應該在測試長度的if內。

是否打印“未找到空文件”的測試是錯誤的。 $currentfiles是所有文件的列表,而不是空文件。 並且您的測試是倒退的:您正在測試變量是否為空。 當你找到一個空文件時,你應該做的是設置一個變量。 然后在循環完成后,您可以檢查該變量。

有一個內置的測試文件是否具有非零大小,您不需要為此使用du

你不應該解析ls的輸出,使用通配符。

如果您要打印一條消息說移動成功,您應該實際檢查它是否成功。

詢問他們是否要移動文件的問題並沒有說明它是哪個文件。

emptyfound=n
for eachfile in *
do
    if [ ! -s "$eachfile" ] # check if any files are empty
    then
        emptyfound=y
        echo -n "Would you like to move the file $eachfile Y/N:" # if a file is empty ask the user if the want to move the file
        read useranswer

        if [ "$useranswer" = "y" ] || [ "$useranswer" = "Y" ]
        then
            if mv "$eachfile" /home/student/Empty_Files
            then echo "mv command successful"
            else echo "mv command failed"
            fi
        else
            echo "File will not be moved"
        fi
    fi
done

if [ "$emptyfound" = n ]
then
    echo "no empty files found in the current directory"
    #exit 55
fi

這實際上是為參加技術學院課程的學生進行的練習。 Barmar,您已經確定了需要進行的更改。 我是講師——我不認為我有提交這個來看看學生是否獲得滿分! :) 我看到他們也發帖求助於同一個班級的其他一些作業。 猜猜我需要睜大眼睛 - 我確實說過他們可以在互聯網上找到“靈感”,但需要引用 URL - 不知何故不認為有人會發帖讓其他人解決他們的問題。 (廢話)

暫無
暫無

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

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