Why do I get "Permission denied" when redirecting the output of sudo echo "xyz" to a file?

20,984

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)

Share:
20,984

Related videos on Youtube

amphibient
Author by

amphibient

Software Engineer with table manners

Updated on September 18, 2022

Comments

  • amphibient
    amphibient over 1 year

    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?