Directory Unix Shell脚本-expr语法问题

Directory Unix Shell脚本-expr语法问题,directory,size,expr,Directory,Size,Expr,我正在尝试查找当前目录的总大小,但shell脚本在expr命令处失败。下面是我的代码: #!/bin/sh echo "This program summarizes the space size of current directory" sum=0 for filename in *.sh do fsize=`du -b $filename` echo "file name is: $filename Size is:$fsize" sum=`expr $sum

我正在尝试查找当前目录的总大小,但shell脚本在expr命令处失败。下面是我的代码:

#!/bin/sh
echo "This program summarizes the space size of current directory"

sum=0

for filename in *.sh
do
    fsize=`du -b $filename`
    echo "file name is: $filename Size is:$fsize"
    sum=`expr $sum + $fsize`        
done
echo "Total space of the directory is $sum"

du返回大小和文件名,您只需要总大小。 尝试更改您的fsize分配

fsize=$(du -b $filename | awk '{print $1}')
目录内容的总大小,不包括子目录和目录本身:

find . -maxdepth 1 -type f | xargs du -bS | awk '{s+=$1} END {print s}'

du将给出目录使用的实际空间,因此我必须使用“find”来真正匹配文件,使用awk来添加大小。

尝试
du-bsomefile
。它将打印大小和名称,如下所示:

263     test.sh
然后,您尝试将大小和名称以算术方式添加到
sum
中,这是行不通的

您需要将文件名切掉,或者使用而不是
du

fsize=`stat -c "%s" $filename`
…对于
bash
有一种更简洁的计算方法,如下所述:

输出:

This program summarizes the space size of current directory
file name is: t.sh Size is:270
Total space of the directory is 270

当我执行时,它抛出“expr:syntax error”。您可以使用
du-cb*.sh
执行同样的操作。你还想实现什么?关于你的陈述的问题“du-b--summary-S | awk{print$1}”问题。下面是ls-l-a的输出:4096 Jan 26 22:06。4096年1月26日22:06。。346 Jan 20 01:26 BreakContinue.sh 805 Jan 17 01:23 DirectorySize.sh 597 Jan 19 02:22示例1.sh 1245 Jan 13 01:54 fileprocess.sh 325 Jan 12 23:31 first1.sh 477 Jan 14 02:29 LineCount.sh 27 Jan 20 02:44 Outfile.txt 446 Jan 16 20:56 Pattern Match.sh 719 Jan 18 01:54 RetireAge.sh 409 Jan 21 02:01 SizeSum1.sh 420 Jan 26 22:06SizeSum.sh 142 Jan 13 21:04 sum.sh[edureka@localhost脚本]$du-b--summary-s10054。输出应该是“5958”。为什么是10054?是的,这很奇怪;我运行了“find.-maxdepth 1-typef | xargs du-bS | awk'{s+=$1}END{print s}'”,将当前目录中所有内容的字节相加,结果比“du-Sb--summary”小12354字节。看看我能不能弄明白。这里有点猜测,但是我在不指定文件的情况下使用
du
将包括目录本身使用的实际空间,以及文件。我正在更新我的答案。。。
This program summarizes the space size of current directory
file name is: t.sh Size is:270
Total space of the directory is 270