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
$
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.
sudo code . It is recommended to start vscode as a normal user. To run as root, you must specify an alternate user data directory with the --user-data-dir argument.
From VS Code Start VS Code. Press F1, select Remote-WSL: New Window for the default distro or Remote-WSL: New Window using Distro for a specific distro. Use the File menu to open your folder.
Make sure that you (as an Ubuntu user account) are the owner of the folder and files you are editing in VSCode: cd /path/to/my/files chown -R $USER:$USER . Note: If you are not the user, you might have to precede that with sudo : sudo chown -R $USER:$USER .
You can own the file you want to edit, then give it back the ownership afterwards
sudo chown myuser /path/to/file
code /path/to/file
sudo chown root /path/to/file
I got the same error , i was not able to save any file in vscode after editing and it was resolved by the following command :
sudo chown -R <user-name> <directory-name>
It worked for me , Hope it works for you too. Thank you
Set environment variable:
export VISUAL="code -nw"
Then you can edit any file like this:
sudo -e file
It will automatically make a copy of file, and, when you close the editor, copy it back.
Currently, the only way I was able to achieve this was to use rmate.
sudo wget -O /usr/bin/rmate https://raw.githubusercontent.com/aurora/rmate/master/rmate
sudo chmod a+x /usr/bin/rmate
I'm using a Debian Buster WSL here, however you can replace /usr/bin
with an appropriate folder in your $PATH depending on your OS or your preference.
make sure the Extension is enabled on WSL: after adding the plugin.
Here is how I configured the remote VS Code plugin
File -> Preferences -> Settings
Press F1 and run Search for the Remote: Start Server
command.
Start your WSL instance and open a terminal. If you've done everything correctly you should be able to now edit your files with sudo priveledges in your editor, even if you are not the root user.
sudo rmate /etc/profile.d/custom-profile.sh
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With