简体   繁体   中英

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

I am trying to compare the stat output with the integer. 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. What is the problem with the code?

You need command substitution to save the STDOUT (or STDERR) of a command in a variable:

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:

$ 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.

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 ?

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$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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