`sudo code` in WSL2 doesn't work? Short guide to the rescue

pushkarski

Nikita Pushkarski

Posted on August 30, 2021

`sudo code` in WSL2 doesn't work? Short guide to the rescue

If you are one of those guys who are on Windows and have been struggling with making the sudo code . or sudo code {file_path} commands work, you've come to the right place.

DISCLAIMER

I myself know the basics of vi/vim, but it's much more convenient for me to create/format/update configs using VS Code. I'm sure there are a lot of people out there who can do things in vi/vim faster than I do in VS Code. Good for them. This short how-to aims only to reach people who, like me, like to use WSL2 and VS Code. This article doesn't seek to compare text editors, ignite pointless holy wars, or sth like that.

Why?

WSL2 gave us a wonderful opportunity to launch VS Code right from the Linux subsystem. That means that you can open some Linux-related config file not in vi/vim/nano, but in VS Code, then change and save it there AS ROOT. And it works. On paper.

In reality, I wasn't able to use it in the way I've just described. After a couple of tweaks, the 'code .' command started to work properly, but I was still far from saving Linux files in VS Code. By spending some additional time, I made it work, finally.

My setup

  • Windows 10 21H1 build 19043
  • WSL2 with Ubuntu 20.04.3 LTS
  • VS Code 1.59.1

Without further ado, here are the steps you need to perform on your Windows machine to tame this naughty WSL2.

Repeat after me

  1. In VS Code, install the Remote - WSL extension.
  2. In Windows, add the following line to your PATH environment variable: C:\Users\Your User Name\AppData\Local\Programs\Microsoft VS Code. Don't forget to substitute your user name here! Windows PATH environment variable
  3. In WSL2, add the following lines to the ~/.profile:
    • alias code="code.exe"
    • alias sudo="sudo " <-- there's a space before a closing quote, don't omit it.
  4. Restart your WSL2 session or open a new one.
  5. Run code . to open the current folder in VS Code; run code {file_path} to open the specified file in VS Code.
  6. You're awesome!

Useful links

šŸ‘‰ Official docs on using VS Code in WSL2
šŸ‘‰ The explanation of the "sudo " trick

šŸ’– šŸ’Ŗ šŸ™… šŸš©
pushkarski
Nikita Pushkarski

Posted on August 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related