visual-studio-codesudowindows-subsystem-for-linuxvscode-remote

VSCode in WSL: how to sudo a root file so I can edit it


WSL v.1 -- VSCode v1.40.1 (using 'Remote - WSL' extension 40.3)

How to open a root-owned file for edit using sudo and VSCode? (without running as root)

If I open a root file without sudo, I can't edit it (expected): $ code /etc/profile.d/custom-profile.sh $

enter image description here

But, if I try to sudo code the file, I get:

$ sudo code /etc/profile.d/custom-profile.sh
[sudo] password for xxxx:
sudo: code: command not found

Binarify's answer below shows that I can switch the default user to root, but I definitely don't want to be running as root, so I'm still looking for another solution.


Solution

  • Changing the user to root doesn't seem like a good solution. As Barafu Albino said, you need to set the SUDO_EDITOR environment variable.

    For me, the solution looks like this:

    export VS_CODE="/mnt/c/Users/alex/AppData/Local/Programs/Microsoft\ VS\ Code/bin/code"
    export SUDO_EDITOR="${VS_CODE} -nw"
    

    You may use $ which code to find the VScode binary in Linux or where code in the Windows CMD. Make sure you don't forget to escaped the spaces in the resulting path.

    export SUDO_EDITOR="code -nw"

    Finally, you can edit the files with sudo -e /path/to/file.