-1

I tried making a file in a root directory, but even when using Sudo, it says I don't have permission.

Making the directory and file:

$ sudo mkdir /VM
$ sudo touch /VM/hi
$

Trying to echo to file:

$ echo "hi" > /VM/hi
warning: An error occurred while redirecting file '/VM/hi'
open: Permission denied
$ sudo echo "hi" > /VM/hi
warning: An error occurred while redirecting file '/VM/hi'
open: Permission denied
$

Should I change the file and directory's permissions? If so, what would the command for that be?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Use `sh` if using redirects: `sudo sh -c 'echo "hi" > /VM/hi'`. – Wiimm Aug 13 '23 at 12:38
  • Redirection is done by the shell. Your shell attempts to open the file for redirection _before it executes `sudo`_. It's not `sudo` that's opening it (nor the command that `sudo` executes, i.e. `echo`). – Toby Speight Aug 13 '23 at 12:52
  • I assume that you are not using `bash`. – Cyrus Aug 13 '23 at 13:52

2 Answers2

1

$ sudo tee /VM/hi <<< "hi"

When you run this command with sudo, it will write the text "hi" to the file located at /VM/hi, and since you're using sudo, the command will have the necessary permissions to write to that location. Just make sure the path /VM/hi exists and that you have the appropriate permissions to write to it.

Elie Hacen
  • 372
  • 12
0

In your last example, echo is executed with root user but > redirection is made by your local bash with current user.

If you need to read a file with root user and write with root user without new shell or command between quotes:

sudo cat /root/file.txt | sudo tee /root/output.txt >/dev/null

or reverse (as you want):

sudo tee /root/output.txt >/dev/null < <(sudo cat /root/file.txt)

You could replace sudo cat /root/file.txt sentence by any command you want.

Arnaud Valmary
  • 2,039
  • 9
  • 14