Harness the Combinatoric Power of Command-Line Tools and Utilities
Editing Files You Don't Own with sudo
Published February 4, 2021
A couple of tricks to change files you don't own.
Sometimes you have to make changes to a file you don’t own. You know that you can use
sudo to elevate your privileges, but you might not always want to open the file with a visual editor. Sometimes you want to append something to the file or make a change with another text processing tool.
I’m going to create a small configuration file in the
/var folder on the system. I’ll run
sudo because the
/var folder is owned by the root user; I don’t have access to put things in there myself.
sudo nano /var/config.yml
I’ll add a couple of lines to it:
api_key: 12345 user: brian
Then I’ll save the file and exit the editor. We’ll do the rest of the work through CLI commands.
First, let’s try to add a new line to the file. Your first thought might be to use
echo to append text to the file:
echo "path: /var/www" >> /var/config.yml
Remember that two arrows appends text to the file.
But if you try that it doesn’t work. If you don’t own that file, or don’t have access to that file, you can’t modify it.
So you’re probably thinking you have to use
sudo echo "path: /var/www" >> /var/config.yml
But unfortunately that fails too!
The reason is that
sudo is applied only to the
echo command. The redirection happens after the
echo command has completed. The redirection happens under your normal account.
To get around this, you could use
sudo to copy the file to your local directory, make the changes, and then put it back.
But let’s look at a couple of shortcuts instead.
If you only need to store or add text to a file you don’t own, you can use the
echo "path: /var/www" | sudo tee -a /var/config.yml
tee command takes the incoming data from standard output and sends it to the screen and a file simultaneously. And you can call it with
sudo so you’ll get the elevated privileges you need. The
-a flag tells
tee to append the content. If you leave this flag off, it will overwrite the file.
If you look at the file’s contents, you’ll see the new line is at the end of the file.
api_key: 12345 user: brian path: /var/www
The other way you can work with files you don’t own is to use
sudo to launch a subshell:
sudo bash -c 'echo "src: github.com/rails/rails" >> /var/config.yml'
Look at the file again, and you’ll see the new line at the end:
api_key: 12345 user: brian path: /var/www src: github.com/rails/rails
This method has the added benefit of letting you use other commands too. For example, you can use
sed to replace a line in the file. I’ll replace my username:
sudo bash -c 'sed -i -e 's/brian/bphogan/' /var/config.yml'
And when you look at the file, it’s changed:
api_key: 12345 user: bphogan path: /var/www src: github.com/rails/rails
So there you have it. A couple ways to modify files you don’t own, without having to open your text editor.