cURL错误(26)在使用文件名中的变量时

huangapple go评论71阅读模式
英文:

cURL error (26) when using a variable in filename

问题

curl: (26) 无法打开/读取来自文件/应用程序的本地数据

代码如下:

DATE_NOW=$(date "+%Y%m%d_%H%M%s")

curl -k -4 -v -X POST -H "Authorization: Bearer $API_KEY" -F "file=@/home/user/Documents/ShareX/Screenshots/2023/image_$DATE_NOW.jpg" $API_URL

我怀疑
"$DATE_NOW"
可能是问题所在,但是在同一脚本中使用如下所示的echo替换所有变量时,一切正常。当我在命令行中单独使用命令而不使用任何变量时,它会正确上传文件。

echo "curl -k -4 -v -X POST -H \"Authorization: Bearer $API_KEY\" -F \"file=@/home/user/Documents/ShareX/Screenshots/2023/image_$DATE_NOW.jpg\" $API_URL"

我已尝试添加花括号,例如
"${DATE_NOW}"

但结果相同。我查看了几篇帖子,包括

[何时在shell变量周围添加引号](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable)

[如何在shell脚本中在curl命令中传递变量](https://stackoverflow.com/questions/13341955/how-to-pass-a-variable-in-a-curl-command-in-shell-scripting)

以及其他几篇帖子,但未能解决问题。
英文:

I am trying to use curl to send an image to an API, but while using it with variables within a shell scripts, I am getting an error.

curl: (26) Failed to open/read local data from file/application

The code looks like this:

DATE_NOW=$(date "+%Y%m%d_%H%M%s")

curl -k -4 -v -X POST -H "Authorization: Bearer $API_KEY" -F "file=@/home/user/Documents/ShareX/Screenshots/2023/image_"$DATE_NOW".jpg" $API_URL

I suspected

"$DATE_NOW" 

to be the issue but using echo as shown below in the same script is replacing all variables correctly. When I use the command without any variables separately in a command line, it correctly uploads the file.

echo "curl -k -4 -v -X POST -H "Authorization: Bearer $API_KEY" -F "file=@/home/user/Documents/ShareX/Screenshots/2023/image_"$DATE_NOW".jpg" $API_URL"

I have tried to add curly braces like

"${DATE_NOW}"

but it has the same result. I have looked at several posts including

When to wrap quotes around a shell variable

How to pass a variable in a curl command in shell scripting

and several others but have failed to solve the problem.

答案1

得分: 1

我使用 Spectacle(在 KDE,Debian 12 上)来截取屏幕截图,作为 cURL 的文件。然而,文件创建可能需要一些时间,cURL 在文件创建之前就被执行了。在 Spectacle 命令之后添加 sleep 1s 到代码中解决了这个问题,现在上传正常工作了。

英文:

I was taking a screenshot using Spectacle (on KDE, Debian 12) as the file for cURL. However, the file creation probably took some time, and the cURL got executed before the file was created. Adding a sleep 1s to the code after the spectacle command resolved the issue and uploads are now working.

huangapple
  • 本文由 发表于 2023年7月3日 14:12:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602223.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定