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
.
Author by
cokedude
Updated on September 18, 2022Comments
-
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 over 9 yearsFor those wondering: these are not multi-line statements!
-
smw over 9 yearsIf 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 }
oripcs | grep -q "Shared" && echo "true" || echo "false"
- see unix.stackexchange.com/a/48536/65304 for example
-
-
Admin about 2 yearsI had the same problem. This solution worked for me. Thanks!