wget - ダウンロード失敗時にファイルを上書きしない

wget - ダウンロード失敗時にファイルを上書きしない

ファイルをダウンロードすると想像してみてください。~/img.txt

wget https://picsum.photos/200 -O ~/img.jpg

画像ファイルが保存されます。もう一度試しましたが、URLが間違っているとしましょう。

wget https://picsum.photooooooos/200 -O ~/img.jpg

これによりファイルが削除/空になります。

URLが404を返す場合、またはダウンロードにエラーがある場合にファイルを上書きしないようにするにはどうすればよいですか?

ベストアンサー1

次のようにいつでも一時ファイルを使用できます。

outFile=img.jpg

# create temporary file in /tmp and store its name in tmpFile
tmpFile=$(mktemp)

if wget https://picsum.photos/200 -O "$tmpFile"; then
   mv -f "$tmpFile" "$outFile" || echo could not replace "$outfile" >&2
else
   echo wget failed with $? >&2
fi
rm -f "$tmpFile"

おすすめ記事