42

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.

  • For those wondering: these are not multi-line statements! – Anthon Oct 9 '14 at 10:45
  • 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 – steeldriver Oct 9 '14 at 12:10
58

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.