cURL Bash将响应正文保存到文件

时间:2019-06-30 17:36:12

标签: linux bash shell ubuntu-16.04

我一直在bash中创建curl,在这里我想使用调用函数save_log()保存到日志文件中,但是当我打开txt文件时,它只是告诉我执行于标题代码响应正文为空白(空)

这是我的脚本:

SECRET_KEY='lolz'
FILE_NAME="test.txt"


function save_log()
{
  printf '%s\n' \
    "Header Code  : $1" \
    "Executed at  : $(date)" \
    "Response Body  : $2" \
    "====================================================================================================="$'\r\n\n'  >> output.log
}

# while IFS= read -r line; do
while IFS= read -r line || [[ -n "$line" ]]; 
    do
      HTTP_RESPONSE=$(curl -L -w "HTTPSTATUS:%{http_code}" -H "X-Gitlab-Event: Push Hook" -H 'X-Gitlab-Token: '$SECRET_KEY --insecure $line 2>&1) &
      HTTP_BODY=$(echo $HTTP_RESPONSE | sed -e 's/HTTPSTATUS\:.*//g') &
      HTTP_STATUS=$(echo $HTTP_RESPONSE | tr -d '\n' | sed -e 's/.*HTTPSTATUS://') &
      echo $HTTP_RESPONSE
      save_log "$HTTP_STATUS" "$HTTP_BODY" &
done < $FILE_NAME

这是输出

    Header Code  : 
    Executed at  : Mon Jul 1 07:01:40 WIB 2019
    Response Body  : 
    =====================================================================================================

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

只需删除控制操作符 &,即可强制您的命令在后台运行,并且与您自己的脚本控制流异步运行。

这将导致不带任何参数地调用您的save_log()函数(因为它们在后台,并且在您调用save_log()时甚至没有完成)。

我进行了测试,并且可以正常工作(我不知道FILE_NAME上有哪些URL,因此我只添加了一些随机URL)

SECRET_KEY='lolz'
FILE_NAME="test.txt"


function save_log()
{
  printf '%s\n' \
    "Header Code  : $1" \
    "Executed at  : $(date)" \
    "Response Body  : $2" \
    "====================================================================================================="$'\r\n\n'  >> output.log
}

# while IFS= read -r line; do
while IFS= read -r line || [[ -n "$line" ]]; 
    do
      HTTP_RESPONSE=$(curl -L -w "HTTPSTATUS:%{http_code}" -H "X-Gitlab-Event: Push Hook" -H 'X-Gitlab-Token: '$SECRET_KEY --insecure $line 2>&1)
      HTTP_BODY=$(echo $HTTP_RESPONSE | sed -e 's/HTTPSTATUS\:.*//g')
      HTTP_STATUS=$(echo $HTTP_RESPONSE | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')
      echo $HTTP_RESPONSE
      save_log "$HTTP_STATUS" "$HTTP_BODY"
done < $FILE_NAME

输出:

Header Code  : 200
Executed at  : Sun Jun 30 18:05:12 UTC 2019
Response Body  : <!DOCTYPE html> (...)