Bash if 语句 [: 缺少 `]' 错误

Bash if 语句 [: 缺少 `]' 错误

我在使用 bash 时遇到了麻烦。我试图将命令放入if语句中,然后将其与字符串进行比较。

这非常有效。

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

当我将其放入if声明中时,我遇到了一些问题。

$ 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

我尝试过===因为-eq我不确定该使用哪一个。

答案1

你的错误是因为你需要在和missing ]'之间有一个空格,所以该行应该是."Shared"]if [ "$(ipcs | grep Shared | awk '{print $2}')" == "Shared" ]; then

相关内容