Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

How can I get the PID of the GNOME Terminal instance I'm using from within a Bash script?

I can run xprop _NET_WM_PID and then manually click the terminal window, but I'd like to completely automate this.

share|improve this question

2 Answers 2

There are times when more than one instance is running — when I have a terminal open in a guest session, for example

The variable $PPID will give you the parent process for the current bash shell, which is often gnome-terminal.

To be safe though, the following will find the parent gnome-terminal process even if multiple bash shells are nested:

pstree -p -s $PPID | grep -Po 'gnome-terminal\(\K.*?(?=\))'


The following universal version will work for any shell, even if other grep instances are running. Deciphering it is left as an exercise for the reader ;)

pstree -p -a -s \
$(pstree -p -a | grep -B3 $RANDOM$RANDOM \
| grep -m1 `echo $SHELL |cut -d/ -f3` | cut -d, -f2)\
| grep gnome-terminal | cut -d, -f2
share|improve this answer
    
True, but I think any method that assumes there is only one GNOME Terminal instance is still fundamentally flawed. Another counterexample: gnome-terminal --disable-factory –  ændrük May 20 '12 at 1:02
    
See edited answer ;) –  izx May 20 '12 at 2:28
up vote 1 down vote accepted

This solution feels the most robust to me. It recursively looks up the parent PID until finding one that belongs to GNOME Terminal.

find-parent() {
    i=($(ps -o pid= -o ppid= -o cmd= -p $1))
    ((i[0] == 1)) && return 1
    if [[ ${i[2]} =~ (^|/)gnome-terminal$ ]]; then echo ${i[0]}; else find-parent ${i[1]}; fi
}; find-parent $PPID
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.