开发者

If condition issue in shell

I'm trying to detect whether a string holds a dash but 开发者_StackOverflow社区nothing seems to work for me (I'm new to shell).

if [ "$m" -eq "-" ]
then
echo "has dash"
else
echo "has no dash"
fi


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜