3

I'm currently studying shell commands, one of the exercises consists in creating a structure with various directories and subdirectories.

I wrote ls -laR > hello, it was supposed to create a text file named hello. However, I get the following message bash: hello: permission denied, even when I type sudo in the beginning.

The command worked in another Linux distribution. Also, I used a few minutes ago ls -la in the directory where I want to create the file and it gave me this:

drwxr-xr-x 2 root root 4096 Nov 26 10:56 .
drwxr-xr-x 5 root root 4096 Nov 26 10:56 ..

According to the first triad I have writing privileges?

6
  • 1
    ls -laR > hello works on my Ubuntu if I issue it in my home dir. Best you can do is show us the permissions of the directory you are in :)
    – Rinzwind
    Nov 26, 2013 at 15:15
  • Maybe reason is in place where you are trying to create that files? I tried this on my Xubuntu 13.10 and it was working in my home folder, but directly on disk (/) i had the same message, also sudo didn't help.
    – dhpasta
    Nov 26, 2013 at 15:20
  • What path you are? Is the partition mounted as read-only?
    – Braiam
    Nov 26, 2013 at 15:57
  • @Rinzwind I posted the directory permissions.
    – sUnTECH789
    Nov 26, 2013 at 16:05
  • What is the output of echo $USER $PWD?
    – Braiam
    Nov 26, 2013 at 16:05

2 Answers 2

17

Because root is the owner of the directory where you want to create hello file and users from the same group and other users doesn't have permission to write in that directory, you will get bash: hello: permission denied error when you run ls -laR > hello.

Moreover, you will get exactly the same error when you run the same command using sudo in front of it. This because output redirection (the > operator) is done by the shell, not by ls, so sudo has no effect upon it. sudo has effect only on ls -laR. To prevent this, you have to login as root:

sudo -i

Then you can use redirection:

ls -laR > hello

Otherwise, you can run your bash command in a subshell with root privileges:

sudo bash -c "ls -laR > hello"

Finally, another option, instead to use redirection via the > operator, you can use tee command:

ls -laR | sudo tee hello

You don't have to use in this case sudo for ls command because users from the same group with root and all other users have read and execution permission in that directory.

3

Either put the hello file in a writable directory like with:

ls -laR > /tmp/hello

or, if you really want to create a file in a directory you don't own, run:

sudo sh -c "ls -laR > hello"

Not the answer you're looking for? Browse other questions tagged .