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.
Best Answer
You can check if the parent process is the shell. For example:
ps -o ppid:1= -p $$
prints the PID of the parent process (ppid
) of the current process (-p $$
). Areadlink
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 haveSHLVL
2 or greater. When run by double clicking, or from a desktop launcher, it should be 1: