首页 > 解决方案 > Shell-Script:如果用户错误,则获取 cURL 错误

问题描述

我的 shell 脚本如下所示:

#!/bin/bash
curl -f -T /home/skript_1.txt -u XXX:XXXXXXX! -k http://192.168.0.100/home/test.txt
res=$?
if test "$res" != 0; then
   echo "the curl command failed with: $res"
else
   echo "Success $res"
fi

我用它来处理文件...

现在我的问题是,我无法得到所有错误。例如,如果我输入了错误的 URL(正确的 URL 是http://192.168.0.100:5005/home/test.txt),上传失败,但退出代码仍然是 0。

这是带有错误 URL 的输出:

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx</center>
</body>
</html>
Success 0

我怎样才能得到这些错误呢?

我也用 cURL 和 ftp 目标尝试了同样的事情,它适用于所有错误。

标签: shellcurlerror-handling

解决方案


-w 'http_code %{http_code}'curl在输出末尾添加 HTTP 状态代码。

也许你可以选择这个新版本,我只对它进行了部分测试:

#!/bin/bash
serverResponse=$(curl -f -w 'http_code %{http_code}' -T /home/skript_1.txt -u XXX:XXXXXXX! -k http://192.168.0.100/home/test.txt)
res=$?
if test "$res" != 0; then
   printf "the curl command failed with: %s\n" "${res}"
else
   http_code="${serverResponse##*http_code }"
   if [[ ! -z "${http_code}" && "${http_code}" -ne 200 ]] ; then
     printf "Server sent back this http status: %s\n" "${http_code}"
   else
     printf "Success %s\n" "${res}"
   fi
fi

推荐阅读