linux - [Solved-5 Solutions] How to use sudo to redirect output to a location in Linux ? - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

To find myself quite often needing to redirect output to a location but don't normally have write access to.

The trouble is, the following example doesn't work:

sudo ls -hal /root/ > /root/test.out
click below button to copy the code. By - Linux tutorial - team

You just receive the response:

-bash: /root/test.out: Permission denied

How can you get this to work?

Linux - Solution 1:

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 -c option:
sudo sh -c 'ls -hal /root/ > /root/test.out'
click below button to copy the code. By - Linux tutorial - team
  • Create a script with your commands and run that script with sudo:
#!/bin/sh
ls -hal /root/ > /root/test.out
click below button to copy the code. By - Linux tutorial - team

Run sudo ls.sh.

  • 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]$
click below button to copy the code. By - Linux tutorial - team
  • 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
click below button to copy the code. By - Linux tutorial - team

The redirect to /dev/null is needed to stop tee from outputting to the screen. To append instead of overwriting the output file (>>), use tee -a or tee --append (the last one is specific to GNU coreutils).

Linux - Solution 2:

sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
click below button to copy the code. By - Linux tutorial - team

This could also be used to redirect any command, to a directory that you do not have access to. It works because the tee program is effectively an "echo to a file" program, and the redirect to /dev/null is to stop it also outputting to the screen to keep it the same as the original contrived example above.

Linux - Solution 3:

sudo ls -hal /root/ | sudo dd of=/root/test.out
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 4:

sudo bash <<EOF
ls -hal /root/ > /root/test.out
EOF
click below button to copy the code. By - Linux tutorial - team

Or of course:

echo 'ls -hal /root/ > /root/test.out' | sudo bash
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 5:

Make sudo run a shell, like this:

sudo sh -c "echo foo > ~root/out"
click below button to copy the code. By - Linux tutorial - team

Related Searches to - linux - linux tutorial - How to use sudo to redirect output to a location in Linux ?