Find maximum positive integer value in Bourne Shell

后端 未结 3 537
隐瞒了意图╮
隐瞒了意图╮ 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:18

    The Bourne shell has no facilities for storing or manipulating numbers - everything is stored as a string. If you are asking about this kind of thing:

    if [ $x -gt $y ]
    

    then that is handled by a separate (in the Bourne shell) executable called test, which has a symbolic link called '['. So your question is really about the limits of the test command, which all the docs I can find seem quite reticent about.

    0 讨论(0)
  • 2021-01-13 17:19

    I'd stay clear of integer limits as they're non portable and problematic

    $ test 123412341234112341235 -gt 1 || echo bash compares ints
    -bash: test: 123412341234112341235: integer expression expected
    bash compares ints
    $ env test 1 -gt 123412341234112341235 || echo coreutils compares strings
    coreutils compares strings
    

    Instead I'd just do as you suggest and do the extra comparison like:

    [ "$limit" ] && [ $count -gt $limit ]
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题