I am using OSX on a Mac and use Terminal quite often. I have built a few startup scripts that execute on shell open with the .bash_profile
file. However, I would like to be able to have one of them run only on the open of the first shell session when I launch the Terminal app. I can't figure out how to have it launch just once on Terminal app open (the first bash shell opened) but not on subsequently opened new shells.
1 Answer
Here's how I just did it:
I added this to .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
So, upon launching the terminal the first time, I get this output:
Last login: Mon Sep 26 08:30:42 on ttys001 This is echoed in the first tty opened only
When I open another terminal (and thus have two terminal windows open at the same time) I get this output:
Last login: Mon Sep 26 08:33:43 on ttys000
**How it works:**
Every time a new terminal window is opened `.bash_profile` is sourced. This command
who | grep 'ttys' | wc -l
simply counts the number of terminal windows that are open. If they are lower than 2 (in other words; there is only one terminal window active), then echo This is echoed in the first tty opened only
Version info:
OS X Version: 10.11.5
bash --version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)
- Good work man, works great. The command I wanted to issue actually as a part of the code closes the window it's currently launched in (it's essentially like f.lux for the command line whereby if it's after a certain hour it launches a night themed command line for working late and regular if it's daytime) so that took a little bit of finagling with this solution but I just put a sleep in so that after it opened the second terminal, the first stayed open long enough that the conditional didn't trigger and then it exits the first terminal.– MLPCommentedSep 28, 2016 at 2:51
- @MLP I am glad that you were able to implement it!– anonCommentedSep 28, 2016 at 5:42