【发布时间】:2020-06-08 00:24:58
【问题描述】:
我在 /root/xml-test/ 中有一个目录,其中包含 .xml 文件,每个文件大小为 99MB。
我正在使用if <i>TEST</i> 语句来检查大小是否大于$a。
问题是...... if 语句总是导致 A 大于 B - 即使我为 A 选择了一个较小的数字 - 例如 1。
这是测试自己的脚本。 cmets 中有一个 URL,可以为您的测试创建任意大小的文件。
#!/bin/bash
#This will check the size of the XML files in /root/xml-test
# Script Test Procedures
# Create file of any size
#https://www.ostechnix.com/create-files-certain-size-linux/
xmlpath='/root/xml-test/.'
size=$(find $xmlpath -type f -name '*.xml' -exec du -c {} + | grep total$) ; total=$(echo $size | cut -c 1- | rev | cut -c 7- | rev)
b=$total
echo $total 'size in blocks' && echo "enter a second number";'
read a ;
echo "a=$a";
echo b=$total;
if [ $a > $b ];
then
echo "a is greater than b";
else
echo "b is greater than a";
fi;
【问题讨论】:
-
shellcheck.net 验证您的脚本。
[ $a > $b ]创建了一个文件名,如果文件已经存在则截断, -
查看
find的-printf选项及其%s格式说明符(大小以字节为单位)。 -
[ $a > $b ]根本不做你想做的事;>被视为输出重定向而不是比较运算符。[ $a \> $b ]更接近,但它进行词法比较而不是数字比较(即[ 10 \> 2 ]为假,因为在字符排序顺序中“1”在“2”之前)。此外,没有双引号的变量引用可能会产生奇怪的效果。你真正想要的是[ "$a" -gt "$b" ]。total$也应该用引号引起来(可能是单引号,所以$不能被误认为是 shell 语法)。而且(讨厌)你不需要在行尾使用分号。 -
我已经修复了代码块格式;语法高亮使现在更加明显,因为那里有一个杂散的单引号。
标签: linux bash if-statement find filesize