Windows Terminal and WSL Tips and Tricks
Did you find yourself ever having to set-up your development environment all the time? Well I did as well! What if I could tell you, you could save many minutes each day by automating this? Enter the world of Windows Terminal and WSL! 😎
Requirements
WSL Environment
For this post we will need an initialized WSL environment. To get started feel free to follow my previous blog post which gives you full control of where you want WSL to be installed!
Windows Terminal
If you don't have it yet (you should) go download Windows Terminal or install it with winget install Microsoft.WindowsTerminal
Tips and Tricks
Automating Development Environment Startup
Windows Terminal has a lot of CLI tricks up its sleeves, one of these is that you can use 1 single command to open up your entire development environment. Typically, I make a shortcut with the following command in it that opens up my environment, starts processes and lets me know how I can start my other programs:
CMD /C wt.exe --title "Services" wsl -d "Ubuntu-20.04" -- bash -c "cd ~/ && sudo service postgresql start && sudo service docker start && exec bash"; new-tab --title "Site" wsl -d "Ubuntu-20.04" -- bash -c "cd ~/frontend && sleep 3 && npm run dev"; split-pane -V wsl -d "Ubuntu-20.04" -- bash -c "cd ~/ && sleep 3 && npm run dev"; new-tab --title "Flow Engine" wsl -d "Ubuntu-20.04" -- bash -c "cd ~/backend/dotnet/API && sleep 1 && ./start.sh"; focus-tab -t 0
In the following sections I will dissect some of the tricks used above:
Starting a Service
When WSL boots, not all your services are started automatically. You want to do this but not always adapt the ~/.bashrc
file, so add yourself to sudoers first so you don't have to enter a password all the time and then execute the line below on Windows.
# on WSL
echo "$USER ALL=(ALL:ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/$USER
# on Windows
CMD /C wt.exe --title "Services" wsl -d "Ubuntu-20.04" -- bash -c "cd ~/ && sudo service postgresql start && sudo service docker start && exec bash";
Starting a Program
Besides starting a service you also might want to start your program automatically after navigating to a specific directory. The trick here is to make bash interactive by appending -i
CMD /C wt.exe --title "Services" wsl -d "Ubuntu-20.04" -- bash -i -c "cd ~/ && sudo service postgresql start && sudo service docker start && exec bash";
Printing to Console
You can print to console by just using echo, just don't forget to open an interactive shell afterwards so it doesn't closes.
CMD /C wt.exe --title "Demo" wsl -d "Ubuntu-20.04" -- bash -c "cd ~/ && echo 'hello world' && exec bash"
Open interactive Bash
Sometimes you want to have an interactive bash screen and not just your program running. For this just append exec bash
behind it:
CMD /C wt.exe --title "Demo" wsl -d "Ubuntu-20.04" -- bash -c "cd ~/ && exec bash";