MacOS – close all the instances of google chrome except first

google-chromemacosterminal

I can close google chrome with following bash command:

kill -9 $(ps -x | grep "Google Chrome" | awk "{print $1}")

It closes all instances of google chrome.
But I need command that close all the instances of google chrome except first, because music is playing there and I don't want to stop it.

I use word instance to express new google chrome window which opens after I press super N.

Best Answer

To close all windows except the frontmost window, run:

osascript -e 'tell app "Google Chrome" to close (windows 2 thru -1)'

To close all windows except the window opened first, run a script like this in AppleScript Editor:

tell application "Google Chrome"
    if number of windows < 2 then return
    set min to id of window 1
    repeat with w in windows 2 thru -1
        if id of w < min then set min to id of w
    end repeat
    close (windows where id is not min)
end tell

"Instances" are usually called windows in OS X, and windows are not separate instances of a process like the instances opened by open -n.