Bash if statement [: missing `]' error

170,776

Your missing ]' error is because you need a space at the inbetween "Shared" and ], so the line should be if [ "$(ipcs | grep Shared | awk '{print $2}')" == "Shared" ]; then.

Share:
170,776
cokedude
Author by

cokedude

Updated on September 18, 2022

Comments

  • cokedude
    cokedude almost 2 years

    I am having trouble with bash. I am trying to put a command in an if statement and then compare it to a string.

    This works perfectly.

    echo $(ipcs | grep Shared | awk '{print $2}')
    

    When I put it in an if statement I get some problems.

    $ if [ "$(ipcs | grep Shared | awk '{print $2}')" -eq "Shared"]; then
      echo expression evaluated as true;
    else
      echo expression evaluated as false;
    fi
    bash: [: missing `]'
    expression evaluated as false
    
    $ if [ "$(ipcs | grep Shared | awk '{print $2}')" = "Shared"]; then
      echo expression evaluated as true;
    else
      echo expression evaluated as false;
    fi
    bash: [: missing `]'
    expression evaluated as false
    
    $ if [ "$(ipcs | grep Shared | awk '{print $2}')" == "Shared"]; then
      echo expression evaluated as true;
    else
      echo expression evaluated as false;
    fi
    bash: [: missing `]'
    expression evaluated as false
    

    I tried ==, =, and -eq because I wasn't sure which one to use.

    • Anthon
      Anthon over 9 years
      For those wondering: these are not multi-line statements!
    • smw
      smw over 9 years
      If you just want to check whether the string Shared appears in the command output you might want to consider using the exit status of grep directly e.g. ipcs | { if grep -q "Shared"; then echo "true"; else echo "false"; fi } or ipcs | grep -q "Shared" && echo "true" || echo "false" - see unix.stackexchange.com/a/48536/65304 for example
  • Admin
    Admin about 2 years
    I had the same problem. This solution worked for me. Thanks!