Search code examples
powershellwindows-subsystem-for-linuxwindows-terminal

Keep Windows Terminal tab open after invoked WSL command


I'm trying to open a WSL (Ubuntu) tab in Windows Terminal, and then run a command in that tab using WSL. I use the following PowerShell command for that:

wt new-tab -p "WSL (Ubuntu)" wsl echo "hallo"

The problem is, after echo has run, the tab closes immediately. Is there a way to keep it open?


Solution

    • When you pass a command line to wt.exe, the Windows Terminal CLI, it is run instead of a shell, irrespective of whether you also specify a specific shell profile with -p.

    • Thus, to achieve what you want:

      • Your command line must explicitly invoke the shell of interest...
      • ...and that shell must support starting an interactive, stay-open session in combination with startup commands.

    While PowerShell supports this, POSIX-compatible shells such as bash - WSL's default shell - do not.

    A - suboptimal - workaround is the following:

    wt -p 'WSL (Ubuntu)' wsl -e bash -c 'echo ''hello''\; exec $BASH'
    

    Note:

    • Inexplicably, as of Windows Terminal v1.13.11431.0, the ; char. inside the quoted -c argument requires escaping as \; - otherwise it is interpreted by wt.exe as its separator for opening multiple tabs / windows.

    • The above executes the specified echo command first, and then uses exec to replace the non-interactive, auto-closing original shell with an interactive, stay-open session via exec. The limitation of this approach is that any state changes other than environment-variable definitions made by the startup command(s) are lost when the original shell is replaced.

      • A better, but more elaborate solution is possible: create a temporary copy of Bash's initialization file, ~/.bashrc, append your startup commands, and pass the temporary copy's file path to bash's --rcfile option; delete the temporary copy afterwards.