unary operator expected
I am trying to find the output of the following code :
Code:
i=4 j=-1 k=0 ./10aj: line 4: [: -1: unary operator expected 2 ./10aj: line 6: [: -1: unary operator expected 2 ./10aj: line 8: [: -1: unary operator expected 2 where am I making mistake?? what unary operator is 'shell' talking about? |
The script expression has a boolean operator. After the operator, it expects to see a boolean expression. A boolean expression could be either a boolean value, or a more complex expression beginning with a unary operator. Since '-1' cannot be evaluated as a boolean value, it looks for a unary operator. When that fails, it gives the appropriate syntax error.
I'm not sure what you are trying to do. Perhaps you are trying to check if the value is non-zero? |
Maybe you were trying to do:
Code:
#!/bin/bash |
Also, doesn't the dash before the number make test think that it's an option? Or can it somehow figure out that it means "negative"?
|
Quote:
I got used to evaluating expressions like this Code:
[[ $i || $j || $k ]] Code:
[ 4 -a -1 -a 0 ] # this returns an error Code:
[ 4 ] # implicitly assumes [ -n 4 ] Code:
[ 4 -a 0 -a 3] Code:
[ -n 4 -a -n 0 -a -n 3] Code:
$ [ 4 -a -1 -a 0 ] && echo true || echo false Well, that is my theory so far. But it gets even stranger: Code:
$ [ -1 ] && echo true || echo false I had a quick look at the manpage but did not find anything that explains this behavior. Did I overlook something? Other opinions/explanations of the observed behavior are welcome. |
Well interestingly if you use [[]] you get perhaps more informative error messages:
Code:
./d.sh: line 3: conditional binary operator expected does it then become a negative. I am not sure I would call it a bug as perhaps how you would program around this?? |
Quote:
Code:
$ [[ 1 -a 3 -a 4 ]] && echo true || echo false I found the section in bash man-page that describes the intended behavior of '['" Code:
test expr Code:
$ [ 1 -a -1 ] && echo true || echo false To further verify that the second argument is decisive for its behavior when there are three arguments passed, consider the following: Code:
# According to the man-page '-a' can also be a unary operator: Code:
$ ls More fun with unary operators: Code:
$ ls According to the five-or-more-rule the following should have worked: Code:
$ [ \( 1 -a -1 \) -a 4 ] && echo true Apparently, this is not the case. After all, I am more and more inclined to consider this behavior as a bug. Or is my logic failing me? |
I don't quite see the problem. The original post is using '-a' operators with numbers, but they are intended to be used with conditional values. I'll agree that the error message is not very informative, but the only surprising thing is how lenient the shell is.
Code:
[ 0 -a 0 ] && echo true || echo false Code:
[ 4 -ne 0 -o -1 -ne 0 -o 0 -ne 0 ] && echo true || echo false |
Code:
./10a line 4: [: -1: unary operator expected That is all. |
All times are GMT -5. The time now is 02:32 AM. |