Open a URL with parameterized query arguments (URL-encode)

command lineterminalurl

I need to invoke a custom URL for a macOS GUI app from a terminal (shell) command.

I also need to be able to pass arguments to the URL's query section.

It might look like this:

path=/Volumes/MyDisk
what="some text"
open fafapp://find?loc=$path&inp=$what

The problem is that I need to URL-encode path and what first. How can I accomplish this with built-in commands? It should not be necessary to install extra tools for this and should work on macOS 10.11 and later.

I'd also like it consise. It's for instructions to other (non-Terminal-savvy) users for invoking the app via a short shell script, e.g. from automation tools.

Thus, lengthy bash scripts that convert the strings "by hand" are not really a good result for me. Ideally, the open command would be a one-liner.

Best Answer

You have lots of requirements, which makes for a slightly convoluted solution:

open fafapp://find?loc=$(python -c "import urllib, sys; print urllib.quote(sys.argv[1])" "$path")&inp=$(python -c "import urllib, sys; print urllib.quote(sys.argv[1])" "$what")

This uses python, which is pre-installed on macOS 10.11 and later (including Big Sur). It is also a one-liner (although a long one).