Windows Terminal Bash Shell: Open New Tab in Same Directory

When you are using a Windows Subsystem for Linux Bash shell in Windows Terminal, you can use the techniques described in this blog post to open a new tab to the current directory.

In Windows Terminal, you can use keyboard shortcuts such as Ctrl+Shift+1 to open new tabs using the various installed and configured shells. Bash shells always start in your home directory. Sometimes you want to start a new shell in the directory where you are already working.

You can use the following alias to open a new tab in the current directory, but You must type the nt command to create the new tab, then type cd and press Ctrl+V to paste the directory path, and then press Enter.

alias nt='echo -n $PWD | clip.exe ; cd /mnt/c ; cmd.exe /c wt.exe -w 0 nt ; cd - > /dev/null'

The nt command performs the following actions.

  • Write the current working directory without a linefeed that would otherwise cause a prompt.
  • Pipe that value to the Windows clipboard.
  • Change the current working directory to a known Windows directory (C:\) to avoid a warning from the wt.exe command.
  • Start a Windows command shell to run Windows Terminal to open a tab (nt) in the current window (0).
  • Revert the working directory in the original shell tab, omitting the output from this cd command.

Define the alias in your initialization.

Actually, there is another way, but I think that it takes a shell script instead of an alias. If you call this with no arguments, it starts a new bash shell that calls the same script but passes the current working directory as an argument, in which case the script switches to that directory and calls bash.exe, which starts the shell in that directory. Instead of moving to a directory that does not cause an error message, this just hides all error messages from the wt.exe command, but I do not think it is worth changing directories or the effort of grepping out the specific expected error messages.

#!/bin/sh

if [ "$1" = "" ]; then
    cmd.exe /c wt.exe -w 0 nt bash.exe -c "$0 $PWD" 2>/dev/null
else
    cd $1
    bash.exe
fi

It’s weird that you cannot use wt.exe directly to launch a new Windows Terminal or open a tab from within a bash shell, instead resorting to cmd.exe /c.

Here is another command for a new window instead of a new tab.

#!/bin/sh

if [ "$1" = "" ]; then
    cmd.exe /c wt.exe nt bash.exe -c "$0 $PWD" 2>/dev/null
else
    cd $1
    bash.exe
fi

One thought on “Windows Terminal Bash Shell: Open New Tab in Same Directory

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: