【问题标题】:cgi-fcgi script is not executing corectlycgi-fcgi 脚本未正确执行
【发布时间】:2022-01-27 03:51:33
【问题描述】:

我正在使用:

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

使用 /bin/ash shell

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

#!/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

这个脚本有错误吗?

【问题讨论】:

    标签: linux scripting ash


    【解决方案1】:

    条件是语法错误,因为最后一个]]之前缺少空格:

    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"
    

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

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

    【讨论】:

    • 我正在使用:/usr/local/bin # cat /etc/os-release NAME="Alpine Linux" ID=alpine VERSION_ID=3.12.7 PRETTY_NAME="Alpine Linux v3.12" /usr /local/bin # echo $0 /bin/ash 另外,原文没有“Status:200”。因此,如果显示“状态:”,则表示与 200 不同
    • 我用 ash 替换了不正确的 bash 标签(我从未使用过)。不知道你想告诉我什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2014-08-15
    • 2012-02-07
    • 1970-01-01
    • 2012-02-16
    • 2018-02-08
    相关资源
    最近更新 更多