How to determine if a user has selected Run In Terminal

When double-clicking a bash script, Ubuntu asks if the user wants to display, run, or run in the terminal ...

Is there a way in the script to determine if the user has selected "Run In Terminal"?

+4
source share
3 answers

Strictly speaking, you cannot determine whether the user selected “Run In Terminal” after clicking on the script or running the terminal and running the script. But the commands below will help you, especially [ -t 2 ] .

 if [ -t 1 ]; then echo "Standard output is a terminal." echo "This means a terminal is available, and the user did not redirect the script output." fi 
 if [ -t 2 ]; then echo "Standard error is a terminal." >&2 echo "If you're going to display things for the user attention, standard error is normally the way to go." >&2 fi 
 if tty >/dev/null; then echo "Standard input is a terminal." >$(tty) echo "The tty command returns the name of the terminal device." >$(tty) fi 
 echo "This message is going to the terminal if there is one." >/dev/tty echo "/dev/tty is a sort of alias for the active terminal." >/dev/tty if [ $? -ne 0 ]; then : # Well, there wasn't one. fi 
 if [ -n "$DISPLAY" ]; then xmessage "A GUI is available." fi 
+6
source

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.

+1
source

Never tried, but this probably works:

 if [ -t 1 ] ; 

Although this would also be false if the conclusion he conveyed ...

0
source

All Articles