我有一个检查0大小的脚本,但我认为必须有一种更简单的方法来检查文件大小.即file.txt
通常为100k; 如何使脚本检查它是否小于90k(包括0),并使它做一个新的副本,因为在这种情况下文件已损坏.
我目前正在使用的..
if [ -n file.txt ]
then
echo "everything is good"
else
mail -s "file.txt size is zero, please fix. " myemail@gmail.com < /dev/null
# Grab wget as a fallback
wget -c https://www.server.org/file.txt -P /root/tmp --output-document=/root/tmp/file.txt
mv -f /root/tmp/file.txt /var/www/file.txt
fi
Run Code Online (Sandbox Code Playgroud)
Mik*_*kel 233
[ -n file.txt ]
不检查其大小,它检查字符串file.txt
是否为非零长度,因此它将始终成功.
如果你想说"大小不为零",你需要[ -s file.txt ]
.
要获取文件大小,可以使用wc -c
以字节为单位获取大小(文件长度):
file=file.txt
minimumsize=90000
actualsize=$(wc -c <"$file")
if [ $actualsize -ge $minimumsize ]; then
echo size is over $minimumsize bytes
else
echo size is under $minimumsize bytes
fi
Run Code Online (Sandbox Code Playgroud)
在这种情况下,听起来就像你想要的那样.
但是,仅供参考,如果您想知道文件使用了多少磁盘空间,您可以使用du -k
以千字节为单位来获取大小(使用的磁盘空间):
file=file.txt
minimumsize=90
actualsize=$(du -k "$file" | cut -f 1)
if [ $actualsize -ge $minimumsize ]; then
echo size is over $minimumsize kilobytes
else
echo size is under $minimumsize kilobytes
fi
Run Code Online (Sandbox Code Playgroud)
如果您需要更多控制输出格式,您还可以查看stat
.在Linux上,你会从像stat -c '%s' file.txt
BSD/Mac OS X这样的东西开始stat -f '%z' file.txt
.
Dan*_*ral 22
令我惊讶的是,没有人提到stat
检查文件大小.有些方法肯定更好:-s
用于查明文件是否为空是比其他任何方法都容易,如果你想要的话.如果你想找到一个大小的文件,那么find
肯定是要走的路.
我也喜欢du
用kb获取文件大小,但是,对于字节,我会使用stat
:
size=$(stat -f%z $filename) # BSD stat
size=$(stat -c%s $filename) # GNU stat?
Run Code Online (Sandbox Code Playgroud)
fst*_*tab 16
awk和双括号的替代解决方案:
FILENAME=file.txt
SIZE=$(du -sb $FILENAME | awk '{ print $1 }')
if ((SIZE<90000)) ; then
echo "less";
else
echo "not less";
fi
Run Code Online (Sandbox Code Playgroud)
gni*_*urf 11
如果您find
处理此语法,则可以使用它:
find -maxdepth 1 -name "file.txt" -size -90k
Run Code Online (Sandbox Code Playgroud)
file.txt
当且仅当大小file.txt
小于90k时,这将输出到stdout .要执行一个脚本script
,如果file.txt
具有比90K以下的尺寸:
find -maxdepth 1 -name "file.txt" -size -90k -exec script \;
Run Code Online (Sandbox Code Playgroud)
如果您只是寻找文件的大小:
$ cat $file | wc -c
> 203233
Run Code Online (Sandbox Code Playgroud)
小智 7
stat似乎用最少的系统调用来做到这一点:
$ set debian-live-8.2.0-amd64-xfce-desktop.iso
$ strace stat --format %s $1 | wc
282 2795 27364
$ strace wc --bytes $1 | wc
307 3063 29091
$ strace du --bytes $1 | wc
437 4376 41955
$ strace find $1 -printf %s | wc
604 6061 64793
Run Code Online (Sandbox Code Playgroud)
这适用于linux和macos
function filesize
{
local file=$1
size=`stat -c%s $file 2>/dev/null` # linux
if [ $? -eq 0 ]
then
echo $size
return 0
fi
eval $(stat -s $file) # macos
if [ $? -eq 0 ]
then
echo $st_size
return 0
fi
return -1
}
Run Code Online (Sandbox Code Playgroud)
小智 6
python -c 'import os; print (os.path.getsize("... filename ..."))'
Run Code Online (Sandbox Code Playgroud)
可移植的,所有风格的python,避免统计方言的变化