sudo redirection permission denied | use tee or script

The trouble is, this contrived example doesn't work:
sudo ls -hal /root/ > /root/test.out
I just receive the response:
-bash: /root/test.out: Permission denied



There are multiple solutions:
  • Run a shell with sudo and give the command to it by using the -c option:
    sudo sh -c 'ls -hal /root/ > /root/test.out'
    
  • Create a script with your commands and run that script with sudo:
    #!/bin/sh
    ls -hal /root/ > /root/test.out
    
    Run sudo ls.sh. See Steve Bennett's answer if you don't want to create a temporary file.
  • Launch a shell with sudo -s then run your commands:
    [nobody@so]$ sudo -s
    [root@so]# ls -hal /root/ > /root/test.out
    [root@so]# ^D
    [nobody@so]$
    
  • Use sudo tee (if you have to escape a lot when using the -c option):
    sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
    
    The redirect to /dev/null is needed to stop tee from outputting to the screen. To appendinstead of overwriting the 


Comments

Popular posts from this blog

HAproxy logging

tomcat catalina coyote jasper cluster

NFS mount add in fstab _netdev instead of default | firewall-cmd --list-all