As the open
command does not produce the desired results, here is an adaptation of my answer A: Open an URL in Safari with Private Browsing that will easily allow you to open a URL from the command line in a new tab of a Safari window, whether or not a tab with that URL already exists..
It works whether or not Safari is running, and if running, whether or not a window already exists.
In Terminal, run the following compound command:
f='openurl'; touch "$f"; open -e "$f"; chmod +x "$f"
Copy and paste the example AppleScript code, shown below, into the opened openurl document, then save it.
You should then move the openurl
shell script to a directory located within the shell's PATH
.
I moved it to /usr/local/bin
, e.g,:
sudo mv -v openurl /usr/local/bin/
Now from Terminal I can open the same URL in a new tab Safari whether or not a tab with that URL already exists.
Typing just the executable's name without any arguments shows how it can be used e.g,:
% openurl
Missing URL...
Example: openurl 'https://www.example.com'
%
Example AppleScript code:
#!/usr/bin/osascript
on run args
if args is {} then return ¬
"Missing URL..." & linefeed & ¬
"Example: " & (name of me) & space & "'https://www.example.com'"
set theURL to first item of args as string
if not running of application id "com.apple.Safari" then
tell application id "com.apple.Safari"
activate
set i to 0
repeat until exists window 1
delay 0.1
set i to i + 1
if i ≥ 40 then return
end repeat
set URL of current tab of window 1 to theURL
end tell
else
tell application id "com.apple.Safari"
if exists window 1 then
tell window 1 to set URL of (make new tab) to theURL
else
make new document with properties {URL: theURL}
end if
end tell
end if
end run
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5
, with the value of the delay set appropriately.