Set Maximum Time Limit for cURL Operation

When performing network requests with cURL, preventing commands from hanging indefinitely is crucial for script efficiency and system resource management. This article explains how to set a maximum time limit for an entire cURL operation to complete using the --max-time option, provides practical command-line examples, and distinguishes it from connection-specific timeouts.

To set a maximum time limit for the entire cURL operation, use the -m or --max-time option followed by the maximum number of seconds you want to allow the command to run. This timeout covers the entire duration of the transfer, including the connection phase, name lookup, protocol negotiation, and the actual data transfer.

Here is the basic syntax for limiting a cURL operation to 10 seconds:

curl --max-time 10 https://example.com

Alternatively, you can use the short form -m:

curl -m 10 https://example.com

If the transfer does not complete within the specified time limit, cURL will abort the operation and exit with an exit code of 28 (which indicates a operation timeout).

Handling Decimal Values

The --max-time option also accepts decimal values, allowing you to specify sub-second timeouts. For example, to limit an operation to maximum of 2.5 seconds, use:

curl --max-time 2.5 https://example.com

Distinguishing Connection Timeout vs. Total Timeout

It is important to understand the difference between --max-time and --connect-timeout:

For robust scripting, you can combine both options to ensure your script fails fast if the server is unreachable, while still putting a hard limit on the total download time:

curl --connect-timeout 5 --max-time 30 https://example.com

In this example, cURL will abort if it cannot connect to the server within 5 seconds, or if the entire transfer takes longer than 30 seconds.