Skip to content

[MacOS] Automatically Close The Terminal After Executing The Shell Script

Last Updated on 2021-10-02 by Clay

In the Linux operating system, I wrote a lot of scripts to assist with the functions I need in my daily life. And these scripts will automatically execute the program in the background and close the terminal window.

But after I moved my work environment to Mac OS, I found that my old shell scripts can be executed but can not close the terminal window.

After searching on the Internet for a while, I finally found a practical solution in StackOverflow, which is recorded as follows.


Automatically Close The Window After Shell Script Is Executed

Method 1: killall

The simple method is to add at the bottom of the shell script:

killall Terminal

But be careful, this will close all terminals! If you only want to close the current terminal, you can refer to the following record.


Method 2: Adjust the settings, use exit 0 (I can’t succeed)

In Linux, we can use exit to close the terminal. But it is not worked on Mac OS. I saw someone on StackOverflow mentioned that you can modify the settings, so also record it.

But I can not succeed.

Terminal > Preferences > Profiles > Shell > Change “When the shell exits:” option to “Close if the shell exited clearly”

Then, write exit 0 at the bottom of your shell script to exit (it is said).


Method 3: Use AppleScript in shell script to close the terminal that executes the script

This method looks complicated, but in fact it is very simple. Use the following syntax to exit successfully.

osascript -e 'tell application "Terminal" to close (every window whose name contains "YOUR_SCRIPT_NAME")'

Among them, YOUR_SCRIPT_NAME needs to be changed to the name of your shell script to successfully close the specific terminal.

Below I use a program to open a folder as an example.

#!/bin/bash


close() {
    osascript -e 'tell application "Terminal" to close (every window whose name contains "open_folder.sh")'
}

nohup open ./ & close

Then I named the open file open_folder.sh.

The following is the result of program execution:

You can see that the program can automatically close the terminal window and keep the folder open, while the other terminal will not be closed.

Method three is a better solution that I have tried.


References


Read More

Leave a Reply