首页 > 解决方案 > 根据运行时信息构造命令

问题描述

我需要在 ash 中运行一个 shell 脚本。如何解决缺少用于动态构建命令的数组而不会遇到问题的问题?

这是我要修复的代码块:

CURL_ARGS=('--noproxy' '*' '--verbose' '--silent' '--include' '--write-out' '%{http_code}')
if [ "$CURL_HOST_HEADER" != "" ]; then CURL_ARGS+=(--header "$CURL_HOST_HEADER"); fi
CURL_ARGS+=("http://$CURL_HOST:$CURL_PORT$CURL_PATH")

echo Proceeding with curl cmd: curl "${CURL_ARGS[@]}"

n=0
until [ $n -ge 5 ]
do
    n=$[$n+1]
    CURL_RESPONSE=$(curl "${CURL_ARGS[@]}")
    PAGE=${CURL_RESPONSE:0:-3}
    HTTP_STATUS=${CURL_RESPONSE: -3}

    if [ "$HTTP_STATUS" != "200" ]
    then
        echo "Curl failed with http status $HTTP_STATUS. Retrying shortly if attempts remain"
        sleep 15
    else
        break
    fi
done

if [ "$HTTP_STATUS" != "200" ]
then
    LOGFILE=curlable-error-page-$(date +%s).html
    echo "CURL CMD:" > $LOGFILE
    echo "curl ${CURL_ARGS[@]}" >> $LOGFILE
    echo "STATUS:" >> $LOGFILE
    echo "$HTTP_STATUS" >> $LOGFILE
    echo "RESPONSE:" >> $LOGFILE
    echo "$PAGE" >> $LOGFILE
    exit 1
fi

标签: shellash

解决方案


如果没有数组,您的下一个最佳选择是定义一个函数,以便您可以利用其(未使用的)位置参数充当伪数组。

作为示例,我将假装标头作为参数传递,而不是作为全局变量(如主机、端口和路径)进行访问。

run_curl () {
  # save any arguments first
  curl_host_header=$1

  # Repurpose $@ for use when you call curl
  set -- '--noproxy' '*' '--verbose' '--silent' '--include' '--write-out' '%{http_code}'
  if [ -n "$curl_host_header" ]; then
      set -- "$@" --header "$curl_host_header"
  fi
  set -- "http://$CURL_HOST:$CURL_PORT$CURL_PATH" 


  n=0
  until [ "$n" -ge 5 ]
  do
    n=$(($n+1))
    curl_response=$(curl "$@")
    page=${curl_response:0:-3}
    http_status=${curl_response : -3}

    if [ "$http_status" != "200" ]
    then
      echo "Curl failed with http status $HTTP_STATUS. Retrying shortly if attempts remain"
      sleep 15
    else
      break
    fi
  done

  if [ "$http_status" != "200" ]
  then
    logfile=curlable-error-page-$(date +%s).html
    {
      echo "CURL CMD:"
      echo "curl $*"  # $* is fine for embedding in a larger string
      echo "STATUS:"
      echo "$http_status"
      echo "RESPONSE:"
      echo "$page"
    } > "$logfile"
    exit 1
  fi
}

run_curl                      # No extra headers
run_curl "$CURL_HOST_HEADER"  # Extra header 

推荐阅读