skip to Main Content

About this setting in VS Code:

enter image description here

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:

enter image description here

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


  1. 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 the settings.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.

    1. Create a shell script (e.g., open_terminal.sh) in your home directory with the following content:

      #!/bin/bash
      if [ -d "$1" ]; then
        cd "$1"
      else
        cd "$HOME"
      fi
      exec gnome-terminal
      
    2. Give executable permissions to your script:

      chmod +x ~/open_terminal.sh
      
    3. Update your VS Code settings (settings.json) to use this script:

      {
        "terminal.integrated.shell.linux": "/bin/bash",
        "terminal.integrated.shellArgs.linux": ["-c", "~/open_terminal.sh ${fileDirname}"]
      }
      

    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.

    Login or Signup to reply.
  2. 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.

    enter image description here

    If VSCode can’t find the relativeFileDirname there’s another problem at hand.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search