首页 > 解决方案 > 如何在curl中使用变量值作为文件名

问题描述

我正在遍历文件中的 url 以下载它们的数据,每个 url 代表一天中每个小时的数据。我想将文件命名为它来自的日期和时间。以下不起作用,但我不太清楚为什么

myDate=$(date -v -1d '+%Y/%m/%d')
for hour in {0..23}
do
   ...
   ...
   #set file name
   name=$myDate.$hour.txt
   curl -L -o $name "https://..."
done

我认为这只是 curl 语句中 $name 的语法问题,但我不知道如何纠正它。

我收到以下错误

Warning: Failed to create the file 2019/09/18-0: No such file or directory
curl: (23) Failed writing body (0 != 16360)

标签: bashmacosshell

解决方案


date -v -1d '+%Y/%m/%d'返回一个包含斜杠的字符串,斜杠用作路径分隔符,例如,在:

iMac-ForceBru:~ forcebru$ date -v -1d '+%Y/%m/%d'
2019/09/18

2019/09/18被视为18在目录中调用的文件09,而目录又在目录2019中。2019/09您的系统上似乎不存在该路径,因此2019/09/something.txt无法创建该文件。


推荐阅读