How to check whether shell scripts / Vim running in VS Code integrated terminal?
Asked Answered
F

3

9

Issue

Question is as stated in the title.

In gist, I am trying to get my bash scripts and Vim to behave differently when running in VS Code's integrated terminal.

Things I've found

I have managed to find several other Stack Overflow questions, but they relate to detection of operating systems:
- How to check if running in Cygwin, Mac or Linux?
- How to detect the OS from a Bash script?

Fenestella answered 24/8, 2019 at 6:13 Comment(1)
Environment variables are the best way to do that... Can you configure the shell in VS Code to export a unique environment variable you can use for detection? Or can you check the environment in your VS Code shell to see if it already includes a variable you could use for this detection?Erlina
P
21

By examining the shell variables in the vscode terminal you can see that it sets TERM_PROGRAM=vscode. In my .bash_profile I have the following and it works great:

if [ "$TERM_PROGRAM" == "vscode" ]; then
    # some stuff
else
    # other stuff
fi
Preferential answered 8/12, 2019 at 1:13 Comment(0)
M
0

You can check the parent process until it matches or you find PID==1

#! /bin/bash

pid=$$
until (( pid == 1 ))
do
    [[ $(ps -o command= -p $pid) =~ Code ]] && break
    pid=$(ps -o ppid= $pid)
done

(( pid != 1 )) && echo "VS Code"

Check man ps in case yours have different options

Melanochroi answered 24/8, 2019 at 7:18 Comment(0)
N
0

You can check if the TERM_PROGRAM environment variable is set to vscode.

The source code that initializes this variable can be found here in addTerminalEnvironmentKeys in terminalEnvironment.ts.

You can find some examples of shell-specific syntax for checking the value of this environment variable in VS Code's own codebase where it checks the variable to determine whether or not to run its shell integration scripts here, and also in the docs on manually running those shell integration scripts.

I don't think TERM_PROGRAM is defined by any wider standards. It seems to just be a feature that a lot of terminal emulators implement by convention.

There's also a TERM_PROGRAM_VERSION variable if you want to check the VS Code version.

Nervine answered 30/4 at 18:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.