What is the evaluation order of the bash "test" command?

What is the order in which expressions are evaluated testor [evaluated in a bash script? Is it the same as the order in which they are written? Are they all rated?

In the following example:

if [ expr1 -a -n expr2 ]

will expr2 be evaluated if expr1 is false?

+3
source share
1 answer

It has been a long time since I used this particular syntax. Currently, I prefer:

if [[ expr1 && -n expr2 ]]

since I know that they are shorted. The manual page bashindicates:

Operators &&and ||do not evaluate expression2 if the value of expression 1 is sufficient to determine the return value of the entire conditional expression.

, [ test ( -a).

, ( , ), bash.

, . ( ):

static int or() {
    int value, v2;
    value = and();
    if (pos < argc && argv[pos][0] == '-'
      && argv[pos][1] == 'o' && !argv[pos][2])
    {
        advance (0);
        v2 = or();
        return (value || v2);
    }
    return (value);
}

static int and() {
    int value, v2;
    value = term();
    if (pos < argc && argv[pos][0] == '-'
      && argv[pos][1] == 'a' && !argv[pos][2])
    {
        advance (0);
        v2 = and();
        return (value && v2);
    }
    return (value);
}

, .

bash 2.5, 4.1, . .

. : , -a -o test [.

+11
source

Source: https://habr.com/ru/post/1753256/


All Articles