简体   繁体   English

将stat命令的输出与shell脚本中的整数变量进行比较

[英]comparing the output of stat command with integer variable in shell script

I am trying to compare the stat output with the integer. 我试图将stat输出与整数进行比较。 I am not getting the expected output out of it. 我没有得到预期的输出。

XX_CONFIG_LOCATION=/tmp/config.txt
MAXIMUM_FILE_SIZE=123000
FILESIZE= stat --printf=%s $XX_CONFIG_LOCATION

if [[ "$FILESIZE" -gt "$MAXIMUM_FILE_SIZE" ]]
then
   echo "file size is greater"
else
   echo "file size is lesser"
fi

Here output of split command 123784(filesize) but the maximum filesize is 123000. Here expected output is "file is greater " but every time i am getting file size is lesser. 这里输出split命令123784(filesize),但最大文件大小是123000.这里预期的输出是“文件更大”,但每次我得到的文件大小都较小。 What is the problem with the code? 代码有什么问题?

You need command substitution to save the STDOUT (or STDERR) of a command in a variable: 您需要命令替换来将命令的STDOUT(或STDERR)保存在变量中:

FILESIZE=$(stat --printf='%s\n' "$XX_CONFIG_LOCATION")

As it currently stands the variable FILESIZE is set to null and while doing arithmetic comparison the bash keyword [[ giving the right output: 因为它目前的变量FILESIZE被设置为null并且在进行算术比较时bash关键字[[给出正确的输出:

$ foo=                            
$ [[ $foo -gt 4 ]] && echo OK || echo Not OK
Not OK

Also note that, bash (and other shells) does not allow allow space(s) around = in variable declaration. 另请注意, bash (和其他shell)不允许在变量声明中允许空间=

Nothing new , but here is the reason for your failure. 没什么新鲜的,但这就是你失败的原因。 Did you notices where is the file attribute (75 in this case) is squeezed in ? 你注意到文件属性(在这种情况下是75)被挤进去了吗?

Case-I: 案例一:

ola:ola~/.scratch$ stat --printf=%s sample.txt
**75ola**@ola:~/.scratch$

Case-II: 案例二:

ola:ola~/.scratch$ stat --printf='%s\n' sample.txt
75
ola@ola:~/.scratch$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM