There are many scenarios where we think that we have opened a file to make changes to it using the root user but when we actually try saving the changes, we realize that the file was opened with a normal user or with a user that doesn’t have the specific permission to edit the file. In such cases, we usually have only one option and that is to close the file with the command shown below
And then, open the file again with the command shown below
sudo su vi file.txt
Make changes and save the file with the command shown below
While this is all simple, what if we actually want not to make use of the sudo su command and still be able to edit and save the file that doesn’t allow other users except root.
In order to do the same, we can make use of the command mentioned below
:w !sudo tee filename
The above command is a bit complex to understand first, let me break it to you. The :(colon) symbol is what begins the command and then we write w just after it, which stands for write permission, which normally accepts a file path to which to write.
Then, we have !sudo where the sudo keyword is obvious, which allows you to run the command as super-user. The ! symbol is known as the negation symbol, which simply flips the value. Then following the !sudo we have the tee symbol which pipes stdin to the given file, the process goes something like this, the :w will write to stdin, then the super-user tee will receive the file contents and write the file, without creating a new file, simply overwriting the contents and also the file modes and attributes will be preserved.
Now that we know what the command actually does, let’s use of it on a simple file where the file only allows a super-user to edit it.
Consider we have a file in /usr/local/go/src which is the default path of Go's source code. The name of the file is symtab.go which can be found on this location
If we are using any user that doesn’t have the privileges of the super-user and open this file and then try to change the content and save the file with the command shown below
Then we will get the following error −
"symtab.go" E212: Can't open file for writing
This is because we don’t have the permission to make changes to the file, and the workaround is to either use the command that I mentioned above or change the user, since we don’t want to change the user its better to just the command shown below in your terminal
:w !sudo tee symtab.go
And now, we will be able to make any changes we want to the file without having to switch to the super-user.