[url] Passing a URL with brackets to curl

If I try to pass a URL to curl that contains brackets, it fails with an error:

$ curl 'http://www.google.com/?TEST[]=1'
curl: (3) [globbing] illegal character in range specification at pos 29

However, if I escape both brackets, it appears to work:

$ curl 'http://www.google.com/?TEST\[\]=1'

Interestingly, I use a backslash to escape only the first bracket it fails silently with error code 20497:

$ curl 'http://www.google.com/?TEST\[]=1'
$ echo $!
20497

My question is how to fix this for general cases? Is there an argument that will escape URLs automatically, or a description of the characters that need to be escaped before passing to curl?

This question is related to url curl

The answer is


Globbing uses brackets, hence the need to escape them with a slash \. Alternatively, the following command-line switch will disable globbing:

--globoff (or the short-option version: -g)

Ex:

curl --globoff https://www.google.com?test[]=1

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.