首先,如您的问题中所述,没有使用osascript 实现此目的的简洁解决方案。 osascript 本身根本不提供满足您的要求逻辑所需的选项/参数。
但是,以下 bash shell 脚本 (.sh) 避免使用 killall,并会在关闭/退出应用程序之前提示用户保存对文档的任何未保存更改。 (这与关闭计算机时提示用户保存任何未保存的更改非常相似):
close-apps.sh
#!/bin/bash
# Creates a comma-separated String of open applications and assign it to the APPS variable.
APPS=$(osascript -e 'tell application "System Events" to get name of (processes where background only is false)')
# Convert the comma-separated String of open applications to an Array using IFS.
# http://stackoverflow.com/questions/10586153/split-string-into-an-array-in-bash
IFS=',' read -r -a myAppsArray <<< "$APPS"
# Loop through each item in the 'myAppsArray' Array.
for myApp in "${myAppsArray[@]}"
do
# Remove space character from the start of the Array item
appName=$(echo "$myApp" | sed 's/^ *//g')
# Avoid closing the "Finder" and your CLI tool.
# Note: you may need to change "iTerm" to "Terminal"
if [[ ! "$appName" == "Finder" && ! "$appName" == "iTerm" ]]; then
# quit the application
osascript -e 'quit app "'"$appName"'"'
fi
done
注意:在下面的代码行中,我们避免关闭 Finder 和运行命令的 CLI 工具。您可能需要将 "iTerm" 更改为 "Terminal",或者更改为您的 CLI 工具的名称:
if [[ ! "$appName" == "Finder" && ! "$appName" == "iTerm" ]]; then
使 close-apps.sh 可执行
正如answer 中所述,您需要先使close-apps.sh 可执行,然后才能运行它。为此,请通过 CLI 输入以下内容:
$ chmod +x /path/to/close-apps.sh
(/path/to/close-apps.sh 部分应根据脚本的保存位置替换为您的路径)
通过 CLI 运行 close-apps.sh。
您可以通过在 CLI 中输入以下内容来运行 shell 脚本:
$ /path/to/close-apps.sh
(同样,/path/to/close-apps.sh 部分应根据脚本的保存位置替换为您的路径)
通过 Applescript 运行 close-apps.sh。
shell 脚本也可以通过 AppleScript 应用程序执行,只需双击而不是通过 CLI 输入命令。
为此,您需要:
-
打开AppleScript Editor 应用程序,该应用程序位于Applications/Utilities/ 文件夹中。
-
输入以下代码:
on run
do shell script "/path/to/close-apps.sh"
quit
end run
(同样,/path/to/close-apps.sh 部分应根据 .sh 脚本的保存位置替换为您的路径)
-
保存 Applescript 并通过保存对话框选择File Format: Application。我们就叫它closeApps.app吧。
-
最后,close-apps.sh 脚本中的以下代码行应该改成这样:
if [[ ! "$appName" == "Finder" && ! "$appName" == "iTerm" ]]; then
...到这个:
if [[ ! "$appName" == "Finder" && ! "$appName" == "closeApps" ]]; then
注意 Applescript 的文件名(closeApps)替换了iTerm(或Terminal)。
- 要关闭在 Dock 中打开的所有应用程序,您只需双击
closeApps 应用程序图标即可。