簡體   English   中英

Unix Bash Shell腳本文件大小

[英]Unix Bash Shell Scripting File Size

我正在研究一個bash shell腳本,它要求我按給定目錄中的大小順序顯示文件。 如果文件的大小為0,我會詢問用戶是否要刪除它。 到目前為止我有這個:

#!/bin/bash
FILE=$(ls -S $1)
for FIL in ${FILE}
do
    echo ${FIL}
done

這會按大小順序顯示文件,但我不確定如何提示用戶刪除大小為0的文件。

謝謝你的幫助!

因此,如果我們希望盡可能接近您當前的方法,我們可以這樣做:

#!/bin/bash
FILE="$(ls -S "$1")"

for f in $FILE
do
    file_size_bytes=$(du "$f" | cut -f1)
    echo "$f"

    if [[ "$file_size_bytes" -eq 0 ]]
    then
        read -r -p "Would you like to delete the zero-byte file ${f}? [Y/n]: " input

        if [[ "$input" = [Yy] ]]
        then
            rm "$f"
        fi
    fi
done

另一個答案使用stat ,但stat不是POSIX或者是可移植的,但是如果你只是在Linux下運行, stat是一個很好的方法。

在上面的示例中, read -p用於提示用戶輸入,並將結果存儲在$input 我們使用[[ "$input" = [Yy] ]]來查看輸入是Y還是y

它當前的編寫方式,您必須鍵入yY並按Enter鍵刪除該文件。 如果您希望在用戶點擊yY立即發生,請添加-n 1以進行read以使其僅讀取一個字符。

您也不需要使用${var}除非您將其放在另一個字符串中,或​​者您需要使用某種參數擴展。

作為旁注,這聽起來像是某種類型的家庭作業或學習經歷,所以,請查看上面的每個命令,選項和語法元素,並真正了解它是如何工作的。

find /your/path/ -size 0 -exec echo rm -i {} \; # will fail if there are spaces in any file names

更好的方法:

find /your/path/ -size 0 -print0 | xargs -0 rm -i

刪除echo以刪除文件

謝謝@Will,@ AdamKatz。

您可以使用redirection並將stdin重定向到另一個文件描述符,同時為進程替換提供循環以實現您的目標。 例如:

#!/bin/bash

[ -z "$1" ] && {
    printf "error: insufficient input, usage: %s <path>\n" "${0//*\/}"
    exit 0;
}

exec 3<&0   # temprorary redirection of stdin to fd 3

while read -r line; do
    printf " rm '%s' ? " "$line"
    read -u 3 ans   # read answer for fd 3
    anslower="${ans,,}"
    if [ "${anslower:0:1}" = "y" ]; then
        printf " %s  =>  removed.\n" "$line"
        # rm "$line"
    else
        printf " %s  =>  unchanged.\n" "$line"
    fi
done < <(find "$1" -type f -size 0)

exec 3<&-   # close temporary redirection

注意:實際的rm命令已注釋掉,以確保在測試完成之前不會意外刪除所需文件。

示例使用/輸出

$ bash findzerosz.sh ../tmp/stack/dat/tmp/tst/tdir
 rm '../tmp/stack/dat/tmp/tst/tdir/file4.html' ? n
 ../tmp/stack/dat/tmp/tst/tdir/file4.html  =>  unchanged.
 rm '../tmp/stack/dat/tmp/tst/tdir/file1.html' ? y
 ../tmp/stack/dat/tmp/tst/tdir/file1.html  =>  removed.
 rm '../tmp/stack/dat/tmp/tst/tdir/file2.html' ? y
 ../tmp/stack/dat/tmp/tst/tdir/file2.html  =>  removed.
 rm '../tmp/stack/dat/tmp/tst/tdir/file3.html' ? Y
 ../tmp/stack/dat/tmp/tst/tdir/file3.html  =>  removed.
 rm '../tmp/stack/dat/tmp/tst/tdir/file5.html' ? n
 ../tmp/stack/dat/tmp/tst/tdir/file5.html  =>  unchanged.

這將起作用,以測試一個文件大小是否為0(您只需將其包含在循環中)。

myfilesize=`stat -c %s "$FIL"`

if [ $myfilesize = 0 ];then
echo "the file size is zero, do you want to delete it ?"
read -p "yes/no? " -n 1 -r
echo #Move to Next line
if [[ $REPLY =~ ^[Yy]$ ]]
then
    rm "$FIL"
fi
else
echo "File size is not Zero"
fi

暫無
暫無

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

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