问题
Found this error to be quite weird because previously my script was working and but after I moved it from the server I was working on to my local machine, it stopped working and just gave me an 'unexpected operator' error.
# Else if the script is being run in the arrayscripts directory, add /output/ ...
elif [ $basePath == "arrayscripts" ];
then
echo "$dscr has started to run."
cpuPath="`pwd`/output/cpu.binary"
txtPath="`pwd`/output/cpu.txt"
csvPath="`pwd`/output/cpu.csv"
回答1:
If your actual shell is /bin/sh
[contrary to the initial question, but as discussion commentary has made clear], use =
rather than ==
in your test expression:
elif [ "$basePath" = arrayscripts ]
Note that the right-hand side doesn't need to be quoted in this case, since it contains no expansions and no syntactically-sensitive characters.
Alternately, if this issue is reproducible when using bash, the obvious problem is missing quotes.
Use either
[ "$basePath" = arrayscripts ] # this is POSIX compatible
or
[[ $basePath = arrayscripts ]] # this works only with bash
Otherwise, the number of arguments $basePath
expands into is undefined -- it may expand into zero arguments, making the statement
[ = arrayscripts ]
...which would try to use =
as a unary operator, which it isn't...
or if $basePath
contained, say, "true -o bar ="
, it could expand into something like
[ true -o bar = arrayscripts ]
...resulting in program behavior very different from what you actually want.
Bottom line: When writing for shells which follow POSIX rules (basically, anything but zsh or fish), quote your expansions unless you have a specific and compelling reason to do otherwise. (Use of the bash/ksh extension [[ ]]
provides such a reason, by introducing a context in which string-splitting of expansion results and glob expansion don't take place).
回答2:
This is an error you'd get if you were executing the script with a POSIX shell like dash
. dash
is the default /bin/sh
on some platforms such as Ubuntu and Debian.
==
is specific to bash
( Bashism ) and is not compatible with POSIX shells like dash
, which uses only =
to test string equality.
In the context of single brackets, ==
and =
are treated as the same operator in bash
, so either can be used.
回答3:
I managed to get my script working by changing the comparison function from '==' to '=' as suggested by 'alister' in the unix and linux forums ( http://www.unix.com/shell-programming-and-scripting/141856-how-avoid-unexpected-operator-error-when-comparing-2-strings.html ) and so my script looked like this
# Else if the script is being run in the arrayscripts directory, add /output/ ...
elif [ "$basePath" = "arrayscripts" ];
then
echo "$dscr has started to run."
cpuPath="`pwd`/output/cpu.binary"
txtPath="`pwd`/output/cpu.txt"
csvPath="`pwd`/output/cpu.csv"
Hope that if anyone gets this same error as I did, that this answer will help them. .
来源:https://stackoverflow.com/questions/25846454/bin-sh-odd-string-comparison-error-unexpected-operator