Ubuntu – How to detect the number of opened terminals by the user

bashvirtual-terminal

I am using Ubuntu and can manually change the bash shell prompt color to green using

export PS1="\e[0;32m[\u@\h \W]\$ \e[m" 

However, I want the shell prompt color to automatically change whenever I open a new terminal or tab. I am aware that the basic tty TERM has 16 colors, and it's okay to rotate the colors if more than 16 terminals are open. Will the solution also work when I connect through Putty, tmux or screen.

My idea is to write a shell script and place it in .bashrc which detects the new terminal session the user has opened and increment a global counter from \e[0;31m[ to \e[0;47m[. How to detect the number of opened terminals by the user?

Best Answer

If you really need to get the number of terminal you have open, go for counting the files owned by you under /dev/pts (although this might include ones opened by background processes, not by graphical terminal emulators). Alternatively, count the number of child processes of your terminal emulator(s), as shown by Jacob in the first line of his response.

Avoid relying on who's output, and looking for gnome-pty-helper processes, since these don't work in newer gnome-terminal versions.

Note that nowadays pretty much all graphical terminal emulators (including putty) and multiplexers (screen, tmux) support 256 colors. You can get really nice colored prompts if you use this palette.

My recommendation for a very simple solution is to base the color on the current tty line's number. E.g. process the output of the tty command to take the number only and derive the color from that. A certain tty line number is only given to one terminal at a time, you'd have to close that terminal first before the same line number is reissued by the kernel. This, combined with 256 colors, automatically guarantees that you won't see the same color twice at a given time (and even with 16 colors it'd give a quite even distribution). No need for maintaining a global counter, and no need for counting terminals or processes.

Related Question