我可以给
curl -O some_url
写一个函数,如果下载文件目标已经存在,则重命名已经存在的吗?
例如,在空目录中运行
curl -O https://example.com/image.jpg
将创建一个名为 image.jpg
的文件。
我想重复执行
curl -O https://example.com/image.jpg
来重命名现有的 image.jpg
文件,并下载到新的 image.jpg
文件。
我希望这也适用于带有查询字符串的URL(例如
https://example.com/image.jpg?size=m
),因此我还没有找到一种方法来预测curl下载到的文件名。
是的,您可以编写一个 bash 函数来实现此行为。该函数将检查目标文件是否存在,重命名它,然后使用curl -O下载新文件。它还处理带有查询字符串的 URL。
这是一个可能的实现:
download_with_rename() {
url=$1
# Extract the filename from the URL
filename=$(basename "${url%%\?*}")
# Check if the file already exists
if [[ -e $filename ]]; then
# Find the next available filename by appending a number
i=1
while [[ -e "${filename%.*}_$i.${filename##*.}" ]]; do
((i++))
done
mv "$filename" "${filename%.*}_$i.${filename##*.}"
fi
# Download the new file
curl -O "$url"
}