12

Why do I get

-bash: test: Permission denied

when I run

sudo echo "xyz" > test

The directory permissions are:

drwxr-xr-x 3 root root 4096 2014-08-05 16:26 

I have no problem creating a file in the directory using sudo. But why can't I sudo echo into it?

drs
  • 5,453
amphibient
  • 12,472
  • 18
  • 64
  • 88

1 Answers1

17

This happens because you're only running the echo command as root. The output redirection is handled by your (non-root) shell. To avoid this, don't use the shell's redirect and use an actual command to handle the writing: tee. What you want to do can be done as so:

echo "xyz" | sudo tee test > /dev/null

(if you don't redirect the output, tee will output xyz to stdout, too)

ilkkachu
  • 138,973
technillogue
  • 325
  • 2
  • 8