vscode cd to workspace folder

The normal behavior of cd is to is to go back to $HOME. When in the vscode terminal I would like cd to take me to the workspace root. I do not want to use a hotkey or just open another terminal.

As if:

~/path/to/workspace $ cd /tmp
/tmp $ cd foo
/tmp/foo $ cd
~/path/to/workspace $ 

Related: A How to change the terminal to the current directory in visual studio code ? (hotkey) [duplicate] is closed as a dupe of a question I am not asking1.

1"How to quickly change shell folder to match the currently open file". The current file is not the workspace folder.


Solution 1:

Set an environment variable when an integrated terminal is launched and use it in an alias of cd.

vscode settings.json:

"terminal.integrated.env.linux":  {"VSCODE_WS": "${workspaceFolder}"},
"terminal.integrated.env.windows":{"VSCODE_WS": "${workspaceFolder}"},

.bashrc:

# Make `cd` from a vscode terminal go to the workspace root
# Assume the following is in vscode settings:
# "terminal.integrated.env.linux":  {"VSCODE_WS": "${workspaceFolder}"},
# "terminal.integrated.env.windows":{"VSCODE_WS": "${workspaceFolder}"},
# When in filemode / not in a workspace, `VSCODE_WS` is set to the literal `${workspaceFolder}` so we check and ignore that
if [[ -v VSCODE_WS ]] && [[ "$VSCODE_WS" != '${workspaceFolder}' ]]; then
    alias cd="HOME=\"${VSCODE_WS}\" cd"
fi

Works with gitbash too.

I have not tested with multiple folder workspace windows.