Unix Shell 脚本 - expr 语法问题
Unix Shell Scripting - expr syntax issue
我正在尝试查找当前目录的总大小,但 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 returns 大小和文件名,你只需要总大小。
尝试更改您的 fsize 分配
fsize=$(du -b $filename | awk '{print }')
目录内容的总大小,不包括子目录和目录本身:
find . -maxdepth 1 -type f | xargs du -bS | awk '{s+=} END {print s}'
du 将给出目录实际使用的 space,所以我不得不使用 "find" 来真正只匹配文件,并使用 awk 添加大小。
尝试du -b somefile
。它将像这样打印尺寸和名称:
263 test.sh
然后你试图用算术方式将大小和名称加到 sum
上,这是行不通的。
您需要切掉文件名,或者更好的是,使用 stat
而不是 du
:
fsize=`stat -c "%s" $filename`
...对于 bash
有一种更简洁的方法来进行数学描述 here:
sum=$(($sum + $fsize))
输出:
This program summarizes the space size of current directory
file name is: t.sh Size is:270
Total space of the directory is 270
我正在尝试查找当前目录的总大小,但 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 returns 大小和文件名,你只需要总大小。 尝试更改您的 fsize 分配
fsize=$(du -b $filename | awk '{print }')
目录内容的总大小,不包括子目录和目录本身:
find . -maxdepth 1 -type f | xargs du -bS | awk '{s+=} END {print s}'
du 将给出目录实际使用的 space,所以我不得不使用 "find" 来真正只匹配文件,并使用 awk 添加大小。
尝试du -b somefile
。它将像这样打印尺寸和名称:
263 test.sh
然后你试图用算术方式将大小和名称加到 sum
上,这是行不通的。
您需要切掉文件名,或者更好的是,使用 stat
而不是 du
:
fsize=`stat -c "%s" $filename`
...对于 bash
有一种更简洁的方法来进行数学描述 here:
sum=$(($sum + $fsize))
输出:
This program summarizes the space size of current directory
file name is: t.sh Size is:270
Total space of the directory is 270