cgi-fcgi 脚本未正确执行

cgi-fcgi script is not executing corectly

我正在使用:

/usr/local/bin # cat /etc/os-release
NAME="Alpine Linux"
ID=alpine
VERSION_ID=3.12.7
PRETTY_NAME="Alpine Linux v3.12"

和/bin/ashshell

我有一个检查状态的脚本:

#!/bin/sh


full=$(DOCUMENT_URI=/api/$SERVICE_PREFIX/healthz SCRIPT_FILENAME=/app/src/index.php REQUEST_METHOD=GET cgi-fcgi -bind -connect /run/php-fpm/php.sock)

before=${full%$'\r\n\r\n'*}
after=${full#*$'\r\n\r\n'}
stat=$(echo $before | sed 's/.*Status: //' | cut -d " " -f 1)
sub="Status:"


echo "head is: $before"
echo "tail is: $after"
echo "message is: $full"
echo "status is: $stat"
echo "substring is: $sub"
echo "message is: ${sub} ${stat}"



if [[ "$before" == *"$sub"* ]] && [[ "$stat" != "200"]]; then
  exit 1
fi


if [ "$after" != "OK" ]; then
  exit 1
fi

exit

当我执行脚本时,我得到的响应是正确的,但 if 语句不起作用:

/usr/local/bin # ./liveness_probe1.sh
head is: Status: 300 Multiple Choices
X-Powered-By: PHP/7.4.16
Content-type: text/html; charset=UTF-8
tail is: OK
message is: Status: 300 Multiple Choices
X-Powered-By: PHP/7.4.16
Content-type: text/html; charset=UTF-8

OK
status is: 300
substring is: Status:
message is: Status: 300
/usr/local/bin # echo $?
0

当我只执行一个命令时,我得到不同的响应:

/usr/local/bin # DOCUMENT_URI=/api/$SERVICE_PREFIX/healthz SCRIPT_FILENAME=/app/src/index.php REQUEST_METHOD=GET cgi-fcgi -bind -connect /run/php-fpm/php.so
ck
Status: 300 Multiple Choices
X-Powered-By: PHP/7.4.16
Content-type: text/html; charset=UTF-8

OK

这个脚本有没有错误?

条件是句法错误,因为最后一个]]之前缺少白色space:

if [[ "$before" == *"$sub"* ]] && [[ "$stat" != "200" ]]; then
  exit 1
fi

如果您需要 bash 个功能(在本例中为 [[),请使用 #!/bin/bash。你做 stat=$(echo $before | sed 's/.*Status: //' | cut -d " " -f 1) 反对 echo "$before" | cut -d'' -f2 或将其包装在函数中并使用内置函数有点傻:

status_code() {
   local v=${1#* }
   echo ${v%% *}
}

status_code "Status: 300 Multiple Choices"

这会 return 300。我可能不会费心测试“状态:”前缀,如果它是错误的,那么第二个字符串几乎肯定也是这样:

if [ "$(status_code "$before")" != "200" ] || [ "$after" != "OK" ]
then
   exit 1
fi