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.
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 }
oripcs | grep -q "Shared" && echo "true" || echo "false"
- see http://unix.stackexchange.com/a/48536/65304 for example – steeldriver Oct 09 '14 at 12:10