Quit Terminal.app after closing last window

I use Terminal.app on a daily basis, mostly for my research as I am currently building an adjoint of the CMAQ model.  I like to have 4+ windows open at all times while working in Terminal, as it allows me to watch the progress of a simulation while also editing files, compiling, etc.  I have macros setup that will log me into and out of each terminal window.  One of the frustrating things that I ran into was that, after the macro logged me out of the final window, I wanted the Terminal application to quit.  Now, I very easily could have added the Quit Application command to the macro, however I was hoping for a solution that would also work even if the macro wasn’t called.  I surfed the web for a while and found nothing, until I got a response on my post on Apple’s forums.

I am copying te response to this website, however all credit for the material goes to François J. Perreault, who answered the question.

Here’s how to have Terminal quit automatically after closing all your shells:

  1. Create a new text file in your home folder named “autoQuitTerminal.scpt“:
    tell application "Terminal"
     
      --If there is only one tab remaining, and it contains 
      --the word "logout" then this is the final window
      if (count of (tabs of (every window whose visible is true))) = 1 then
           try
                set theContents to words of ((contents of tab 1 of window 1) as Unicode text)
                set exitLastTab to (theContents contains "logout")
           on error
                set exitLastTab to false
           end try
     
           if exitLastTab is true then
                quit
           end if
     
       else if (count of (tabs of (every window whose visible is true))) < 1 then
      --If no window remains open, then obviously we can quit the app.
      --This would occur when the final window is closed without ‘exit’
            quit
       end if
     
    end tell

  2. Make the file executable by running the following command (in Terminal):
    chmod u+x $HOME/autoQuitTerminal.scpt
  3. At the end of the file “~/.bash_profile” add the following paragraph:
    #auto-closing Terminal app on last window
    if [ "$TERM_PROGRAM" == "Apple_Terminal" ] && [ -x $HOME/autoQuitTerminal.scpt ]; then
    
    trap '/usr/bin/osascript $HOME/autoQuitTerminal.scpt' EXIT
    
    fi
  4. In Terminal, go into Preferences and modify the following settings accordingly: 
  5. Quit Terminal

One thought on “Quit Terminal.app after closing last window

  1. We have been traveling now for over 1 year and
    have been to following places which result in these blogs:.
    However this can be difficult to establish, even on popular blogs, without a bit of a push.
    cort.as recently posted..cort.asMy Profile

Leave a Reply

Your email address will not be published. Required fields are marked *