繁体   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