shposix

comparison operator syntax in posix shell


I'm trying to understand the grammar/syntax of the shell command language (to be able to parse it) and I cannot seem to find where the syntax of the comparison operations is defined.

As an example:

x=10
while [ $x -gt 0 ]
do
    #do something
    x=$(($x-1))
done

The syntax for [ $x -gt 0 ] doesn't appear to be defined anywhere in the specification linked above. In fact, the syntax [...] doesn't appear in the grammar rules and ] is missing from the punctuation/operator tokens. The specification doesn't say much about this construction other than [] being used for regular expression brackets and that [, but not ], "may" need to be quoted in strings.

My questions:

  1. Are the comparison operators a part of the POSIX specification or a generally recognized extension? (I expect the former since the example above is based on one given in the POSIX shell command language specification)
  2. Where can I find the syntax for the shell comparison operators, or [...] generally (whether in POSIX or elsewhere)?

Solution

  • Are the comparison operators a part of the POSIX specification or a generally recognized extension?

    There is no special syntax for comparison in the POSIX shell language. [ is the name of a standard utility command and $x -gt 0 ] are its arguments, the closing square bracket is there only for esthetics. The command [ $x -gt 0 ] can also be written as test $x -gt 0.

    Where can I find the syntax for the shell comparison operators, or [...] generally?

    XCU Chapter 3, Utilities - test