Search code examples
bashvisual-studio-codeelectroncommand-line-interfacepid

Launching and killing (separately) multiple isolated instances of VS Code from command line


Visual Studio Code supports launching instances of itself via the code CLI tool. You can do something like the following:

$ code /Users/username/projects/dotfiles

And it will open VS Code w/ the appropriate project. Since VS Code is just an Electron app, this spawns a number of separate processes, with the parent process matching something like the following:

/Applications/Visual Studio Code.app/Contents/MacOS/Electron /Users/username/projects/dotfiles

So it seems I have a way of identifying the IDE process from its path argument. However, when I try launching another project the same way, say...

$ code /Users/username/projects/work

There is no additional process that appears with that path argument. It still only shows the first one (projects/dotfiles), even though there are two workspaces open in separate windows.

Ultimately, I want the ability to close/kill an individual project IDE window via bash/CLI. Is there some way of starting the 2nd VS Code project in new process such that its path shows up as a command argument in ps, and therefore can be killed independently of the others?


Solution

  • The only viable way I could get this to work was to create a JXA/Applescript function that took project names as an argument, and then cycle through the windows and closing them if their window name contained the project name:

    #!/usr/bin/env osascript -l JavaScript
    
    run = argv => {
      system = Application('System Events')
      vscode = system.processes['Code']
      vscode.windows().forEach( window => {
        argv.forEach( projectName => {
          if(window.name().includes(projectName)) {
            window.buttons.at(0).click()  
          }
        })
      })
    }
    

    Created a file containing that, chmod +x to make it executable, and then you can just do ./closeCode.jxa ProjectName1 ProjectName2 etc. This cleanly closes the window, and if any unsaved files exist, will prompt to save them first.