I´m trying to count how many shell or terminal windows are currently running.
I tried ps a|grep bash;
ps a|grep tty;
But it can be inaccurate.
ls /dev/pts/ | wc -l
Use the above command to count the terminal windows open.
To list them:
ps aux | awk '{print $7}' | grep -v "?"
To count them:
ps aux | awk '{print $7}' | grep -v "?" | wc -l
You will need to subtract 1 from that number as it includes the top TTY header.
This all depends if you are wanting to count how many sub shells are running or if you are wanting to count how many terminal windows are open.
To count just the terminal windows you would need to use:
ls /dev/pts/ | wc -l (stated in a previous answer)
For example:
On my system there are currently six tty's available. I also have one terminal open pts/0 that has 4 processes running in the fg or bg.
root 4565 0.0 0.0 4060 576 tty1 Ss+ May01 0:00 /sbin/mingetty /dev/tty1
root 4567 0.0 0.0 4060 572 tty2 Ss+ May01 0:00 /sbin/mingetty /dev/tty2
root 4569 0.0 0.0 4060 568 tty3 Ss+ May01 0:00 /sbin/mingetty /dev/tty3
root 4571 0.0 0.0 4060 576 tty4 Ss+ May01 0:00 /sbin/mingetty /dev/tty4
root 4573 0.0 0.0 4060 576 tty5 Ss+ May01 0:00 /sbin/mingetty /dev/tty5
root 4575 0.0 0.0 4060 572 tty6 Ss+ May01 0:00 /sbin/mingetty /dev/tty6
me 17482 0.0 0.0 110236 1136 pts/0 R+ 11:36 0:00 ps aux
root 20374 0.0 0.0 108336 1816 pts/0 Ss May23 0:00 -bash
root 20953 0.0 0.1 161436 1960 pts/0 S May23 0:00 su - me
me 20954 0.0 0.1 108524 1984 pts/0 S May23 0:00 -bash
If you want to take away the background child processes then just pipe to uniq:
ps aux | awk '{print $7}' | grep -v "?" | uniq | wc -l
You still have to subtract 1 for the header title of TTY, but you can further improve this by taking the tty's out altogether as it appears you don't care about those anyways.
ps aux | awk '{print $7}' | grep -v "?" | grep -vi "tty*" | uniq
That will give you an accurate count.
EDIT
Thinking about it more 'ps -a' would work better and you can leave out the first grep.
ps a | awk '{print $2}' | grep -vi "tty*" | uniq | wc -l
grep
and awk
is redundant, use awk '/pattern/
; and this doesn't work on my machine - it reports 19 when I have 1.
Commented
May 29, 2014 at 18:21
On macos you can use:
cnt=$(w -h | grep "^$(whoami) *s[^ ]* *-"|wc -l)
echo "Your current terminal sessions: $cnt"
Found here: https://stackoverflow.com/a/6180547/6320039
You can add the \l
option in your PS1 variable, example:
export PS1="terminal #\l \W \$ "
That will count your terminals starting from zero.
More about it in the GNU website.
Hope this helps.
expect
emulated user session,xterm
not running a shell, etc count?