我正在编写一个 Bash shell 脚本,需要按文件大小顺序显示给定目录中的文件。如果文件大小为 0,则需要询问用户是否要删除。目前我的脚本如下:
#!/bin/bash
FILE=$(ls -S $1)
for FIL in ${FILE}
do
echo ${FIL}
done
这会按大小顺序显示文件,但我不确定如何提示用户删除大小为0的文件。
谢谢你的帮助!
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
删除文件时,请去除回声
感谢@Will、@AdamKatz。
rm -i
吗? - Benjamin W.如果我们想尽可能地接近您当前的方法,我们可以这样做:
#!/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
-b
去掉,它的功能仍然是一样的;“bytes”是默认行为。我在我的答案里刚刚把它去掉了。没有 -b
更具可移植性。找得好! - Willfor f in $FILE
会发生什么?也许可以考虑设置 IFS
? - David C. Rankinls
的输出;我没有。shellcheck
比那个更好地警告了我 ;) 但目标是对OP的解决方案进行最小限度的更改。如果是我,我也会使用相同的命令管道获取大小和文件名,然后在IFS= while read line; ...
中解析它。 - Will您可以利用重定向
并将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
--printf "%s"
能用吗?不过,是的,stat
不太可移植,主要是Linux的东西。这就是我选择 du -b
的原因,它是符合POSIX标准的! :) - Will
ls
命令的输出。 - miken32