views:

60

answers:

3

Hi all,

I'm trying to detect whether a string holds a dash but nothing seems to work for me (I'm new to shell).

if [ "$m" -eq "-" ]
then
echo "has dash"
else
echo "has no dash"
fi
+4  A: 

-eq is used for testing equality of integers. To test for string equality, use = instead:

if [ "$m" = - ]

See the man page for test for further details.

Phil Ross
Important note: if `$m` is the empty string, this will evaluate to a syntax error. To prevent that, a common idiom is to test `if [ "x$m" = x- ]`.
Adam Rosenfield
Actually, with the `"$m"` quotes around `$m`, there will be an empty string on `[`'s `args` list, and therefore no syntax error. The reason for quoting stuff beginning with `x` is to prevent the problems when `$m` starts with a `-` and `[` interprets it as a command line switch.
ndim
@Adam I don't get a syntax error in bash (version 3.1). The empty double quotes are treated as the first argument.
Phil Ross
@ndim I also don't see any problems when `$m` starts with a `-`.
Phil Ross
I personally have not observed problems either, but then I have not tested a similar number of Unix shells the Autoconf people need their shell code run on. In http://www.gnu.org/software/hello/manual/autoconf/Limitations-of-Builtins.html, they write that Posix says `[ "..." = "..." ]` should work for every possible string, but in reality, you do run into issues on some systems if the string starts with `-`.
ndim
+2  A: 
if [ "x$m" = "x-" ]; then
    echo "is a dash"
else
    echo "is not a dash"
fi

Uses string comparison, quotes everything, and avoids possible [ command line switch confusion (on some not-quite-Posix shells) if $m starts with a -.

ndim
+1  A: 

The '-eq' operator performs an arithmetic comparison. You need to use the '=' operator instead. ie:

if test "$m" = '-'; then echo "is a dash"; else echo "has no dash"; fi

Howard Hong