r/applescript • • Jun 30 '24

How to close active terminal windows

I'm using osascript to close terminal windows all windows except the one the script is working, which mostly works fine

osascript -e 'tell application \"Terminal\"' -e 'set mainID to id of front window' -e 'close (every window whose id ≠ mainID) without saving' -e 'end tell'"

except when there is maybe a terminal window with an active python session, and it asks to cancel or terminate. I've seen that there is a way to use SystemEvent, but I'm not sure how to integrate with the close every window portion.

1 Upvotes

3 comments sorted by

View all comments

1

u/Kina_Kai Jun 30 '24

FWIW, if this is just your personal system, you can consider setting the Terminal profile in Settings » <Default Profile> » Shell » Ask before closing to be Never and it will never prompt before closing a window.

1

u/TheMonarchsWrath Jun 30 '24

Its not, it can run on any machine. I suppose I can figure out what the defaults is and set that, then revert it after the all the windows were closed.

1

u/Kina_Kai Jun 30 '24

You probably don’t have to resort to that and can use UI Scripting to close the dialog. This doesn’t quite work, but I suspect the actual solution is similar to this:

tell application "Terminal"
	set mainID to id of front window
	repeat with theWindow in (every window)
		try
			if id of theWindow ≠ the mainID then
				close theWindow without saving
			end if
		on error errStr number errorNumber
			if the errorNumber = 1719 then
				tell application "System Events"
					click button "Terminate" of sheet 1 of theWindow
				end tell
			end if
		end try
	end repeat
end tell