goe
goe

Reputation: 5435

If condition issue in shell

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

Upvotes: 1

Views: 539

Answers (3)

Howard Hong
Howard Hong

Reputation: 271

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

Upvotes: 1

ndim
ndim

Reputation: 37905

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 -.

Upvotes: 2

Phil Ross
Phil Ross

Reputation: 26120

-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.

Upvotes: 4

Related Questions