Ubuntu – Using sudo su for commands

command line

I was working on developing my command line skills last night and ran into an issue where when I used sudo, I got an error message that said 'permission denied'. However when I used 'sudo su' and became root the command worked.

Why didn't sudo work in the first instance?

It was:

$ sudo cat > /var/www/info. php
<?php
phpinfo( ) ;
? >
^D

From the Linux Bible 2010 edition in the section on setting up a LAMP server.

Best Answer

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.

Related Question