OSX bash 腳本在 Terminal.app 開啟時執行一次

OSX bash 腳本在 Terminal.app 開啟時執行一次

我在 Mac 上使用 OSX,並且經常使用終端機。我建立了一些啟動腳本,這些腳本在使用.bash_profile檔案開啟的 shell 上執行。但是,我希望能夠在啟動終端應用程式時僅在第一個 shell 會話開啟時運行其中一個。我不知道如何讓它在終端應用程式開啟(第一個 bash shell 開啟)時啟動一次,但不在隨後開啟的新 shell 上啟動。

答案1

這是我剛剛做的:

我將此添加到.bash_profile

# Only do this in the first terminal opened
termsOpen=$(who | grep 'ttys' | wc -l)

if (( $termsOpen < 2 )); then
    echo "This is echoed in the first tty opened only"
fi

因此,第一次啟動終端時,我得到以下輸出:

Last login: Mon Sep 26 08:30:42 on ttys001
This is echoed in the first tty opened only

當我打開另一個終端機(因此同時打開兩個終端機視窗)時,我得到以下輸出:

Last login: Mon Sep 26 08:33:43 on ttys000

**它是如何運作的:**
每次打開一個新的終端視窗時,都會取得`.bash_profile`。這個命令
who | grep 'ttys' | wc -l

只是計算打開的終端機視窗的數量。如果它們低於 2(換句話說;只有一個終端視窗處於活動狀態),則 echoThis is echoed in the first tty opened only



版本資訊:

OS X 版本:10.11.5

bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)

相關內容