Do not download file with curl if file already exists locally

curl

I am currently doing with curl:

curl https://example.com/file -o file

If I already have a file called file in my directory, it will be overwritten by this command. Instead, I would like to return an error message telling that the file already exists.

Is it possible to do so only using curl? I have not seen a flag to do it and I am not running the command in a bash script thus I cannot use a comparison operator before running the command.

Best Answer

Testing for the existence of a name in a directory may be done with the -e test:

if [ -e "filename" ]; then
    echo 'File already exists' >&2
    exit 1
fi

curl -o "filename" "URL"

If you don't want to terminate the script at that point:

if [ -e "filename" ]; then
    echo 'File already exists' >&2
else
    curl -o "filename" "URL"
fi

The test will be true if the name exists, regardless of whether the name is that of a regular file, directory, named pipe or other type of filesystem object.

See man test on your system.

Related Question