Quantcast
Channel: Bash: How to determine whether terminal is opened by third-party app - Ask Ubuntu
Viewing all articles
Browse latest Browse all 5

Answer by Peter Cordes for Bash: How to determine whether terminal is opened by third-party app

$
0
0

If you're talking about one specific third-party app, then use an environment variable. Most programs will pass along the entire environment unchanged when they fork+exec new processes.

So, start this app with a custom env var you can check for. e.g. make an alias for it like alias vs=RUNNING_FROM_VSCODE=1 VSCode, or make a wrapper script like this:

#!/bin/sh
export RUNNING_FROM_VSCODE=1
exec VSCode "$@"

Then in your .bashrc, you can do

if (($RUNNING_FROM_VSCODE)); then
   echo "started from inside VSCode"
   # RUNNING_FROM_VSCODE=0  # optional if you only want the immediate child
fi

A bash arithmetic statement (( )) is true if the expression evaluates to a non-zero integer (which is why I used 1 above). The empty string (for an unset env var) is false. It's nice for bash boolean variables, but you could just as easily use true and check for it with a traditional POSIX

if [ "x$RUNNING_FROM_VSCODE" = "xtrue" ]; then
   echo "started from inside VSCode"
fi

If your app mostly clears the environment for its children, but still passes on $PATH unchanged, you could use this in your wrapper:

#!/bin/sh
export PATH="$PATH:/dev/null/RUNNING_FROM_VSCODE"
exec VSCode "$@"

and check for it with a pattern-match like bash [[ "${PATH%RUNNING_FROM_VSCODE}" != "$PATH" ]] to check if stripping a suffix from PATH changes it.

This should harmlessly do one extra directory lookup when the program is looking for not-found external commands. /dev/null is definitely not a directory on any system, so it's safe to use as a bogus directory that will quickly result in ENOTDIR if PATH searches don't find what they're looking for in earlier PATH entries.


Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>