Find the answer to your Linux question:
Results 1 to 4 of 4
Hello, I want to check for a string in if condition string = "a b c d" if [ $string == "a b c d" ];then echo MATCH else echo ...
  1. #1
    Just Joined!
    Join Date
    Jun 2010
    Posts
    9

    Exclamation String Comparision

    Hello,
    I want to check for a string in if condition
    string = "a b c d"

    if [ $string == "a b c d" ];then
    echo MATCH
    else
    echo DIFFERENT
    fi

    Its giving an error in if statement ( too many arguements)
    Do I need to use regex for that comparison as string also have spaces between them?

  2. #2
    Linux User
    Join Date
    Jan 2005
    Location
    Saint Paul, MN
    Posts
    262
    Quote Originally Posted by ashishmann View Post
    Hello,
    I want to check for a string in if condition
    string = "a b c d"

    if [ $string == "a b c d" ];then
    echo MATCH
    else
    echo DIFFERENT
    fi

    Its giving an error in if statement ( too many arguements)
    Do I need to use regex for that comparison as string also have spaces between them?
    The problem that you are seeing is that the value of "string" is expanded in the statement before it is evaluated. In your case the statement would be (assuming string is "a b c d"):
    Code:
    if [ a b c d == "a b c d" ] ; then
    And as you see it is not a string to string comparison. To allow it to work do either of the following:
    Code:
    if [ "$string" == "a b c d" ] ; then
    or
    Code:
    if [ "${string}" == "a b c d" ] ; then

  3. #3
    Just Joined! AlphaLexman's Avatar
    Join Date
    Aug 2010
    Posts
    1
    Quote Originally Posted by ashishmann View Post
    string = "a b c d"
    Also, make sure you do NOT put [spaces] around the equal sign...
    Code:
    string="a b c d"

  4. #4
    Just Joined!
    Join Date
    Jun 2010
    Posts
    9
    Thanks..It Worked..

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...