Using sudo su for commands?

Solution 1:

The <, > and >> are used for input / output redirection for commands - which is a feature provided by the shell (e.g., bash). So if you type a command like sudo cat > /var/www/info.php then the shell that receives this as input tries to open the file /var/www/info.php and provides that file as the standard output to the sudo command. The sudo command is not even aware whether its output is going to a console or redirected to a file, because this is taken care of by the shell that invokes it.

If the shell you typed your command into is your login shell or another shell running in a terminal with your user id, then it has same privileges as your user id - not those of root.

So in your case, whereas the cat command is executed as root, the copying of its output to /var/www/info.php is attempted by the shell running as a normal user, which, as expected, fails.

A workaround for such situations is to use the tee command :

sudo tee /var/www/info.php

That will have the intended effect of putting all the text entered at the console upto ^D into the file specified as parameter.

One perhaps undersirable side-effect is that tee will also echo the output to the stdout, so after you type each line and press enter tee will output a copy of it back. To avoid this you can use the following variant.

sudo tee /var/www/info.php > /dev/null

Details about tee can be had via info tee at a terminal.

Solution 2:

sudo does not work for commands that need permissions to write a file, such as:

sudo echo "vm.swappines = 100" >> /etc/sysctl.conf

It explains in the sudo man-page.