3

Feeling pretty dumb. With the same user I am able to edit a file via vi, but I get permission errors when appending to the file. What am I doing wrong. I would like to append to this file!

ls -alt /var/log
drwxr-xr-x 11 root      root     4096 May 14 01:20 .
-rw-rw-r--  1 root      root        6 May 14 01:20 money-worker.log

sudo echo "hello" >> /var/log/money-worker.log
-bash: /var/log/money-worker.log: Permission denied

whoami
ubuntu

I am running ubuntu 12.04, and sshing in

Love some tips. Thanks guys!

Jonathan
  • 16,077
  • 12
  • 67
  • 106

2 Answers2

3

Because:

sudo echo "hello" >> /var/log/money-worker.log

means:

( sudo echo "hello" ) >> /var/log/money-worker.log

not:

sudo ( echo "hello" >> /var/log/money-worker.log )

In other words, the appending is being attempted by the shell before sudo runs. The shell will (attempt to) open the file for append then "attach" that to the sudo stanadard output.

As a workaround, you could try something like:

sudo bash -c 'echo "hello" >> /var/log/money-worker.log'

which will run the entire bash-with-arguments-and-redirections under the control of sudo.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • I guess this is why you have greater than 250k! Thanks alot for the quick response AND the quick edits to include the work around! – Jonathan May 14 '13 at 02:01
  • And for those that are dealing with this with upstart (init conf files). This is important to read as well: http://stackoverflow.com/a/8903051/192791 – Jonathan May 14 '13 at 13:26
0

This is because your sudo call affects echo but not the permission on the file. In other words the command executes and then outputs (and sudo ends) then it tries to redirect that output to the file.

You could get around this by putting echo "hello" >> /var/log/money-worker.log into a file and then doing sudo yourscript.sh

Or just change ownership of the file

Cfreak
  • 19,191
  • 6
  • 49
  • 60