How to open multiple URLs in a new Chrome window from the terminal

google-chrometerminal

I can open multiple URLs in the current Chrome window from the terminal:

open https://www.apple.com/ https://www.apple.com/ https://www.amazon.com/

When I tried to open them in a new window using

open -n https://www.apple.com/ https://www.apple.com/ https://www.amazon.com/

Chrome responds with only a blank new window.

How can I open all of the URLs in a new window?

Best Answer

The lazy solution

Use AppleScript to make the new window, then use open without the -n:

osascript -e 'tell app id "com.google.chrome" to make new window' \
  && open https://www.apple.com/ https://www.apple.com/ https://www.amazon.com/

As soon as the window has opened, chances are that Chrome will use it for all the URLs. However, that solution is prone to race conditions, especially if another window is created or activated while your command runs.1

[1] In practice, there are several scenarios where this can happen, e. g. if you run your command in parallel, or if Chrome tries to recover its windows after a crash, or when the user (or another program) attempts to open a new window, etc.

The more robust solution

A more robust alternative, which does not have the race condition mentioned above, is the following all-AppleScript solution:

#!/usr/bin/osascript
on run(theUrls)
    tell app id "com.google.chrome" to tell make new window
            repeat with theUrl in theUrls
                set newTab to make new tab with properties { url: theUrl }
            end repeat
            tell tab 1 to close
    end tell
end run

Save that code, preferably as a file without extension (e. g. open_new_window). Place that file somewhere into your PATH. Make sure to chmod 755 the script so it’s executable. For good measure, I’d recommend to also sudo chmod root:wheel it.

From now on, you can invoke the script like so:

open_new_window https://www.apple.com/ https://www.apple.com/ https://www.amazon.com/

In case you don’t want to use a separate script

Use the following variant for testing, or if you prefer a command line without a separate script:

osascript \
  -e 'on run(theUrls)' \
  -e '  tell app id "com.google.chrome" to tell make new window' \
  -e '    repeat with theUrl in theUrls' \
  -e '      set newTab to make new tab ¬' \
  -e '        with properties { url: theUrl }' \
  -e '    end repeat' \
  -e '    tell tab 1 to close' \
  -e '  end tell' \
  -e 'end run' \
  https://www.apple.com/ https://www.apple.com/ https://www.amazon.com/