In my Bash script, I have a function to return 0 or 1 (true or false) for the later main function’s condition.
function1 () {
if [[ "${1}" =~ "^ ...some regexp... $" ]] ; then
return 1
else
return 0
fi
}
Then in my main function:
main () {
for arg in ${@} ; do
if [ function1 ${arg} ] ; then
...
elif [ ... ] ; then
...
fi
done
}
However, when I ran this script it always gave me an error message:
[: function1: unary operator expected
How can I fix this?
You are making the common mistake of assuming that
[is part of theifcommand’s syntax. It is not; the syntax ofifis simplyOne of the common
commands we use is[which is an alias for the commandtest. It is a simple command for comparing strings, numbers, and files. It accepts a fairly narrow combination of arguments, and tends to generate confusing and misleading error messages if you don’t pass it the expected arguments. (Or rather, the error messages are adequate and helpful once you get used to it, but they are easily misunderstood if you’re not used.)In your
mainfunction, the call to[appears misplaced. You probably meanBy the way, for good measure, you should also always quote your strings. Use
"$1"not$1, and"$arg"instead of$arg.The historical reasons for
testas a general kitchen sink of stuff the authors didn’t want to make part of the syntax ofifis one of the less attractive designs of the original Bourne shell. Bash andzshoffer alternatives which are less unwieldy (like the[[double brackets in bash, which you use in yourfunction1definition), and of course, POSIXtestis a lot more well-tempered than the original creation from Bell Labs.As an additional clarification, your function can be simplified to just
That is, perform the test with
[[and reverse its result code. (The “normal” case would be to return 0 for success, but maybe you are attempting to verify that the string doesn’t match?)