I want to do something like this:
if [ (! true) -o true ]
then
echo "Success!"
else
echo "Fail!"
fi
But it throws an error (-bash: syntax error near unexpected token '!'
)
Is it possible to 开发者_开发技巧do anything like this?
The problem here is that [
is a simple buildtin command in bash (another way to write test
), which can only interpret whatever parameters it gets, while (
is an operator character. The parsing of operators comes before command execution.
To use (
and )
with [
, you have to quote them:
if [ \( ! true \) -o true ]
then
echo "Success!"
else
echo "Fail!"
fi
or
if [ '(' ! true ')' -o true ]
then
echo "Success!"
else
echo "Fail!"
fi
The [[ ... ]]
construct is a special syntactic construct which does not have the syntactic limitations of usual commands, since it works on another level. Thus here you don't need to quote your parentheses, like Ignacio said. (Also, you have to use the &&
and ||
instead of -a
and -o
here.)
You can't do that, but you can do this:
if [ ! true ] || [ true ]
As a general rule, never try to use the -a
or -o
options to [
.
精彩评论