Find maximum positive integer value in Bourne Shell

后端 未结 3 536
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 16:41

I\'m checking a counter in a loop to determine if it\'s larger than some maximum, if specified in an optional parameter. Since it\'s optional, I can either default the maxi

3条回答
  •  醉梦人生
    2021-01-13 17:25

    On my system, the maximum integer of Bash seems to be the same as the LONG_MAX constant of my Perl POSIX library. Obviously, this will vary on your platform, and how your Bash was compiled, etc. But that seems to be a good starting point for testing it:

    declare -i max=$(perl -MPOSIX -le 'print LONG_MAX')
    
    echo $max
    9223372036854775807
    
    echo "max+1 = " $(( i += 1 ))
    max+1 =  -9223372036854775808
    
    uname -a
    Linux x200s 3.2.0-33-generic #52-Ubuntu SMP Thu Oct 18 16:29:15 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
    

    Update: After trying this on an old 32 bit Linux, I see that my Perl's POSIX LONG_MAX is 2147483647, but that Bash still has the same limit. It seems to be defined in /usr/include/limits.h, and to depend on your __WORDSIZE, which may be 64 bits even on 32 bit systems :

    /* Minimum and maximum values a `signed long int' can hold.  */
    #  if __WORDSIZE == 64
    #   define LONG_MAX     9223372036854775807L
    #  else
    #   define LONG_MAX     2147483647L
    #  endif
    

提交回复
热议问题