
是的,我在 Apple Script 的新手體驗很糟糕。
我需要在目前桌面空間中開啟一個新的終端機視窗。不要將我移到另一個正在運行終端的空間,然後打開另一個終端視窗。
當然,如果終端沒有運行,那麼它應該啟動一個新的終端進程。
答案1
tell application "Terminal"
do script " "
activate
end tell
這看起來很奇怪,但它利用了終端如何處理傳入的“do script”命令的奇怪之處;它為每個視窗建立一個新視窗。如果你願意的話,你實際上可以用一些有用的東西來替換它;打開新視窗後它會執行你想要的任何內容。
答案2
如果 do 腳本「」之間沒有任何文本,您將不會在終端機中看到額外的命令提示字元。
tell application "Terminal"
do script ""
activate
end tell
答案3
我可以想到三種不同的方法(前兩種是從其他地方偷來的,但我忘了在哪裡)。我使用第三個,它從 applescript 呼叫 shell 腳本,因為我想每次打開一個新窗口,而且它是最短的。
與至少從 10.10 開始內建於 OS X 的腳本不同,所有這些都在您的查找器視窗中當前工作目錄的任何目錄中開啟終端(即您不必選擇資料夾才能開啟它)。
還包括幾個 bash 函數來完成 Finder > Terminal > Finder 循環。
1. 重複使用現有選項卡或建立新的終端機視窗:
tell application "Finder" to set myDir to POSIX path of (insertion location as alias)
tell application "Terminal"
if (exists window 1) and not busy of window 1 then
do script "cd " & quoted form of myDir in window 1
else
do script "cd " & quoted form of myDir
end if
activate
end tell
2. 重複使用現有選項卡或建立新的「終端」標籤:
tell application "Finder" to set myDir to POSIX path of (insertion location as alias)
tell application "Terminal"
if not (exists window 1) then reopen
activate
if busy of window 1 then
tell application "System Events" to keystroke "t" using command down
end if
do script "cd " & quoted form of myDir in window 1
end tell
3.透過applescript呼叫的shell腳本每次產生一個新窗口
tell application "Finder"
set myDir to POSIX path of (insertion location as alias)
do shell script "open -a \"Terminal\" " & quoted form of myDir
end tell
4.(額外)Bash 別名,用於在終端機中為目前工作目錄開啟一個新的查找器窗口
將此別名加入您的 .bash_profile 中。
alias f='open -a Finder ./'
5. (BONUS) 將終端機視窗中的目錄變更為前端 Finder 視窗的路徑
將此函數新增至您的 .bash_profile 中。
cdf() {
target=`osascript -e 'tell application "Finder" to if (count of Finder windows) > 0 then get POSIX path of (target of front Finder window as text)'`
if [ "$target" != "" ]; then
cd "$target"; pwd
else
echo 'No Finder window found' >&2
fi
}
答案4
上面的答案僅在終端已運行時才有效。否則,它會同時打開兩個終端機視窗 - 一個是因為 ,do script
另一個是因為activate
。
您可以透過簡單的 if ... else 來防止這種情況:
if application "Terminal" is running then
tell application "Terminal"
do script ""
activate
end tell
else
tell application "Terminal"
activate
end tell
end if
獎金:
如果您想直接運行命令,您可以通過擊鍵來完成此操作(不是很優雅 - 我知道!但它有效)
[...]
else
tell application "Terminal"
activate
tell application "System Events" to keystroke "ls -la"
tell application "System Events" to key code 36
end tell
end if