Skip to main content
Quick Tip

How to Set Timeout in cURL

Downloading with curl taking too long? Set a timeout with curl command, so you don't have to wait long.

Team LHB

cURL is an excellent tool for network communications, it stands for 'client URL.' Virtually every device uses cURL on the globe that connects to the Internet. The widest use of cURL is to download files from a remote server in the terminal.

The initial phase of connecting to a server for any sort of communication is waiting for a response. The delay can occur due to a large variety of reasons, some of them being load on the server, network bandwidth, latency, jitter etc.

If the delay is higher than what you would like to wait, you can specify a 'timeout' duration.

The best method of achieving this is by using the --connect-timeout option.

curl --connect-timeout <duration> <URL>

You can specify the timeout in seconds (e.g., 5), in milliseconds (e.g. 0.001), or as a combination of seconds and milliseconds (e.g., 4.20), and curl will use that time as the maximum time for a response until a connection is dropped.

To learn more about setting a maximum timeout in cURL,

Use the '--connect-timeout' option

cURL has an optional flag '--connect-timeout' where you can specify the duration in seconds. If you have a version of cURL that is 7.32.0 or later, you can also specify the duration as decimal values.

The value that you specify will set the maximum time duration to wait for a reply back from the remote server.

Below is an example of how you can use the '--connect-timeout' flag:

curl --connect-timeout 4.2 https://linuxhandbook.com

The use of '4.2' along with the '--connect-timeout' flag means that cURL will try connecting to 'linuxhandbook.com' and if it takes more than 4.2 seconds, the connection will be terminated.

An alternative, '--max-time' option

The '--max-time' flag is used when you are performing multiple operations in a batch. This flag will set the duration for the whole operation - like downloading a big file. So if the operation, like downloading a file, takes longer than the specified amount of time, it will terminate the operation.

$ curl --max-time 20 https://github.com/aristocratos/btop/releases/download/v1.2.3/btop-aarch64-linux-musl.tbz

This example of cURL usage will download a file. When the total time of 'connecting to server' + 'time to download file' is greater than the 20 seconds that we specified here, the download will be terminated.

In this case, the file size is too small for the download to take longer than 20 seconds so that the command will execute successfully.

Conclusion

This article covered how you can set a maximum duration (timeout) for either the time to connect to the remote server or a timeout for the whole network operation.

If you are interested in learning more about cURL, we have covered some of the most common uses of cURL here at Linux Handbook.

Team LHB