Your command does not work because the redirection is performed by your shell which does not have the permission to write to
/root/test.out. The redirection of the output is not performed by sudo.
There are multiple solutions:
Run a shell with sudo and give the command to it by using the
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
sudo ls.sh. See Steve Bennett’s answer if you don’t want to create a temporary file.
Launch a shell with
sudo -sthen run your commands:
[nobody@so]$ sudo -s [root@so]# ls -hal /root/ > /root/test.out [root@so]# ^D [nobody@so]$
sudo tee(if you have to escape a lot when using the
sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
The redirect to
/dev/nullis needed to stop tee from outputting to the screen. To append instead of overwriting the output file
tee --append(the last one is specific to GNU coreutils).
Thanks go to Jd, Adam J. Forster and Johnathan for the second, third and fourth solutions.