The answer @lgeorget provided is very close, but it is still not ideal. The better solution is to use filename_effective
variable for the --write-out
. This is still not completely ideal because it does not work without downloading the file. It is also mentioned in the man curl
:
filename_effective
The ultimate filename that curl writes out to.
This is only meaningful if curl is told to write
to a file with the --remote-name or --output op‐
tion. It's most useful in combination with the
--remote-header-name option.
but if you already have the file in the current folder, then it will throw an error and will discard the downloaded file (in interactive mode it will ask you if you want to overwrite, but in non-interactive mode i.e in a script it throws error):
curl --remote-name \
--remote-header-name \
--location \
--write-out '%{filename_effective}' \
"${URL}"
Therefore, if you want to use it in a script you can do something like:
# just an example URL which will download Bitwarden's CLI software
URL='https://vault.bitwarden.com/download/?app=cli&platform=linux'
TMP_DOWNLOAD_RESULT="$(curl --remote-name \
--remote-header-name \
--location \
--write-out '%{exitcode};%{errormsg};%{filename_effective}' \
"${URL}")"
## break the result into its sub-parts
TMP_EXIT_CODE="$(echo "${TMP_DOWNLOAD_RESULT}" | cut -d ';' -f 1)"
TMP_EXIT_MESSAGE="$(echo "${TMP_DOWNLOAD_RESULT}" | cut -d ';' -f 2)"
TMP_REMOTE_FILE_NAME="$(echo "${TMP_DOWNLOAD_RESULT}" | cut -d ';' -f 3)"
# generate error or message of curl has failed.
if [ "${TMP_EXIT_CODE}" != "0" ]; then
echo
if [ "${TMP_EXIT_CODE}" == "23" ]; then
echo "The local version is already the latest version."
exit 0
else
echo "Downloading with cURL resulted in error number ${TMP_EXIT_CODE} with the message: \n\t${TMP_EXIT_MESSAGE}"
exit 1
fi
fi