About this setting in VS Code:
Is there any way I can use ${fileDirname}
to open in the current file’s path if available, and if not, on the user home as a default? I just switched to Ubuntu from Windows and the behaviour of VSCode integrated terminal with this setting has been bothering me a lot; I can’t open the terminal if I don’t have a file currently open because it shows this error:
And without this setting it prompts me every time to "select current working directory for new terminal", which I also don’t want. Ideally it would be great to open on ${fileDirname} if available, or else on the user home as default behaviour, and not throw an error or prompt me for the folder.
2
Answers
In VS Code, the
${fileDirname}
variable is used to refer to the directory of the file that is currently open in the editor. If you don’t have a file open, VS Code can’t resolve this variable, which leads to the error you’re seeing.To achieve the behavior you’re looking for, where the terminal opens in the current file’s directory if available or in the user’s home directory as a default, you can use a conditional setting in your
settings.json
file for the integrated terminal. VS Code doesn’t support conditional logic natively in thesettings.json
file, but you can work around this limitation with a shell script that checks if the current directory is set and falls back to the home directory if not.Create a shell script (e.g.,
open_terminal.sh
) in your home directory with the following content:Give executable permissions to your script:
Update your VS Code settings (
settings.json
) to use this script:What this setup does is it always executes the
open_terminal.sh
script when you open a new terminal. The script checks if${fileDirname}
is a directory; if it is, it changes to that directory. If not, it defaults to the user’s home directory.Try using
${relativeFileDirname}
instead since the terminal is already setting the base path to the${cwd}
. This works for me as you describe, opens to the current file directory otherwise defaults to the current working directory.If VSCode can’t find the
relativeFileDirname
there’s another problem at hand.