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.
echo "$1"
instead of justecho $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.