Here is an example:
#!/bin/bash GRAND_PARENT_PID=$(ps -ef | awk '{ print $2 " " $3 " " $8 }' | \ grep -P "^$PPID " | awk '{ print $2 }') GRAND_PARENT_NAME=$(ps -ef | awk '{ print $2 " " $3 " " $8 }' \ | grep -P "^$GRAND_PARENT_PID " | awk '{ print $3 }') case "$GRAND_PARENT_NAME" in gnome-terminal) echo "I was invoked by gnome-terminal" ;; xterm) echo "I was invoked by xterm" ;; *) echo "I was invoked by someone else" esac
Now, let me explain this in more detail. In the case when the script is executed by the terminal (in), its parent process is always a shell. This is because terminal emulators run a shell to invoke scripts. Therefore, the idea is to look at the process of grandparents. If the grandparent process is a terminal, you can assume that your script was called from a terminal. Otherwise, it was called by something else, such as Nautilus, which is the default Ubuntu file browser.
The following command gives the parent process identifier.
ps -ef | awk '{ print $2 " " $3 " " $8 }' | grep -P "^$PPID " | awk '{ print $2 }'
And this command gives you the name of the parent parent process.
ps -ef | awk '{ print $2 " " $3 " " $8 }' | grep -P "^$GRAND_PARENT_PID " | awk '{ print $3 }'
And the final switch statement simply compares the grandparent process name with some well-known terminal emulators.
user405725
source share