1

I'd like to open a new (Ubuntu) WSL2 session in Windows Terminal and run a command in it using a script or just a single line of code in Windows Command Prompt.

It seems pretty hard to me. I only got to this:

wt -w 0 nt -p "Ubuntu" -d \\wsl$\Ubuntu\home

where -w 0 tells to create a new tab in existing WT windows (if already present), nt is new-tab command (can be omitted), -p <> indicates the profile to run, -d <> the starting directory.

But how to pass a command to run?

1 Answers1

1

I find it best to have wt launch the wsl.exe command itself, since it has the best "control" over how things are started inside it.

The main issue is typically going to be quoting/escaping.

But let's start with an example that (should) work from the Windows "Run" dialog (Win+R), PowerShell, or CMD:

wt -w 0 nt -p Ubuntu wsl.exe ~ -e bash -c "ls\; sleep 5"

Explanation:

  • This uses the "Ubuntu" profile, but overrides the profile's commandLine setting with the rest of the line.

  • As you noted, the nt (new-tab) here is optional.

  • The wsl.exe ~ starts in your home directory. You could also use --cd /home if you wanted to replicate the -d \\wsl$\Ubuntu\home you are trying in your question.

  • The -e bash starts the Bash shell, passing in ...

  • -c "ls\; sleep 5" to run an ls command wait 5 seconds before exiting the shell (and likely the tab).


Other options/notes:

  • Quoting/escaping is always a bit painful when handing off from CMD (or PowerShell) to WSL/Linux. Note the use of \; to escape the semicolon between bash commands.

  • You could set up a profile with the "Profile Termination Behavior" set to "Never close automatically" and avoid the sleep.

  • The following also works well:

    wt -w 0 nt -p Ubuntu wsl.exe ~ -e bash -c "ls\; exec bash"
    

    This runs the command (ls in this case) and then starts a new Bash shell (replacing the current one) that won't terminate until you exit it.

  • From PowerShell, another quoting option is to use a here string:

    wt -w 0 nt -p Ubuntu wsl.exe ~ -e bash -c @"
      ls
      exec bash
    "@
    
NotTheDr01ds
  • 15,620
  • 5
  • 44
  • 70
  • Ok thank you SO much, now it's definitely clearer. And what about passing a ubuntu cmd as python3 myscript.py? Does this way of proceeding make any sense? I'd like to have a set of python programs running (indefinitely) at startup instead of (each time) starting them manually. Thank you – Stefano Fabbri Mar 06 '23 at 17:21
  • @StefanoFabbri Sure! Just do `wsl.exe ~ -e python3 /path/to/myscript.py`. – NotTheDr01ds Mar 06 '23 at 20:13