0

I have a bash script, which I am trying to create a URL with spaces and other characters that need to be quoted. Is there a simple way to do that?

Essentially, I want to be able to write

#!/bin/sh
arg=$(magic "This has spaces")

curl "https://example.com/some-service?arg=$arg"

and have it execute

curl "https://example.com/some-service?arg=This%20has%20spaces

I could do something like

function magic() {
  echo $1 | sed 's/ /%20/g' | sed s'/\?/%nn/g'
}

and keep adding sed commands as I find more characters that need to be quoted, but it that's annoying, and going to occasionally require me to figure out why the new string isn't working.

If someone has already written that and there is a utility to do the quoting, that would be what I am hoping to find.

I suspect the answer might be python -m magic <maybe more args>, which would be acceptable.

If the best answer is to rewrite the script doing this in Python, I can do that, although I'd like to avoid that if I can.

I tried to google for existing answers, but I found a lot of answers about how to put quotes or spaces into a string, not how to quote spaces.

3
  • Does this answer help? I don't think a pure Bash solution is advisable.
    – BoppreH
    Commented Jul 9 at 15:35
  • Yes. That's what I was looking for and failing to find. Commented Jul 9 at 15:50
  • 1
    @TroyDaniels You should almost always double-quote variable and parameter references (e.g. echo "$1" instead of just echo $1), especially when they might contain funny characters like spaces. Not quoting them can lead to weird bugs. See "When to wrap quotes around a shell variable?". Also, shellcheck.net is good at pointing out common mistakes like this, so I recommend running your scripts through it and fixing anything else it points out. Commented Jul 9 at 16:00

2 Answers 2

3

Here is a way:

curl --data-urlencode 'arg=This has spaces' -G https://example.com/some-service
0
2

You can manages this in bash (does not work for sh)

#!/bin/bash
arg="This has spaces"

curl "https://example.com/some-service?arg=${arg// /%20}"

Another solution is to use curl variable (available since version 8.3.0)

curl \ 
    --variable arg="This has spaces" \
    --expand-url "https://example.com/some-service?arg={{arg:url}}"

More detail can be found here

Not the answer you're looking for? Browse other questions tagged or ask your own question.