Open a file:/// url with #anchor from terminal

I've been trying to open a file:/// url e.g.

open "file:///Users/me/index.html#my-anchor"

Or

open -a Safari "file:///Users/me/index.html#my-anchor"

Or

open -a Google\ Chrome "file:///Users/me/index.html#my-anchor"

However, the browser location after opening is:

file:///Users/me/index.html

The hash/anchor has been clobbered. Is there some way to do this that I'm missing?

(Note: Obviously this isn't what happens with URL's on web servers)


Solution 1:

A non-specific approach is:

 osascript -e 'open location "file:///Users/me/index.html#my-anchor"'

Solution 2:

Don't use the open command.

Google Chrome:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome "file:///Users/me/index.html#my-anchor"

Safari:

osascript -e 'tell application "Safari" to open location "file:///Users/me/index.html#my-anchor2"'

Solution 3:

Taking a stab at narrowing this down: I was getting cryptic errors [1] from this command, and only inconsistently:

osascript -e 'open location "file:///Users/me/index.html#my-anchor"'

Weirdly, that command breaks on file paths containing spaces only if the file path with spaces additionally contains an anchor.

I had no luck with backslash-escaping and quoting the problematic path (more like "'\"Application\\ Sabotage\"'", am I right?), but percent-encoding the spaces to %20 avoided the issue.


[1]: at first, I was only seeing:

execution error: File some object wasn’t found. (-43)

but some attempts at escaping eventually gave me the slightly more helpful:

syntax error: Expected “"” but found unknown token. (-2741)