How to check if script was executed via command line or double-clicked?

How can I determine if a script was invoked from a command line or via double-click in file manager (Nautilis)?

If the former, I still have a command prompt when the script finishes, but if it was double-clicked (or executed via a .desktop file), the script executes in a window and then disappears. I want the window to remain open with a command prompt.

I figure the script could make this check and either do nothing - if invoked from a command line - or exec bash at the end if invoked via double-click or .desktop.

Haven't been successful using methods to check if interactive or not or tty.


You can check if the parent process is the shell. For example:

#! /bin/bash

if [[ $(readlink -f /proc/$(ps -o ppid:1= -p $$)/exe) != $(readlink -f "$SHELL") ]]
then 
    echo "Starting the shell..."
    exec "$SHELL"
else
    echo "Not starting a shell."
fi

ps -o ppid:1= -p $$ prints the PID of the parent process (ppid) of the current process (-p $$). A readlink on /proc/<pid>/exe should print the path to the executable, which would be the shell if you ran it in a shell, or something else otherwise.


Another possibility is the SHLVL variable, which indicates how nested the current the shell instance is. If run within a shell, the script should have SHLVL 2 or greater. When run by double clicking, or from a desktop launcher, it should be 1:

#! /bin/bash

if (( SHLVL > 1 ))
then 
    echo "Starting the shell..."
    exec "$SHELL"
else
    echo "Not starting a shell."
fi

You can check if the shell script was run on a terminal by analyzing the output of tty command.

#! /bin/bash

if [[ $(tty) =~ "not a tty" ]]
then
    echo "Not running on terminal"

else
    echo "Running on terminal"
fi