Why doesnt sudo /dev/null > /var/log/syslog and sudo > /var/log/syslog work, while sudo rm /var/log/syslog works?!

There are two main problems.

One problem is that /dev/null isn't a command, so running sudo /dev/null can't succeed. You need sudo [a command]. In this case, you probably want sudo cat /dev/null.

The other problem is that > separates things into a full command on the left and a file on the right, so the full command on the left is sudo cat /dev/null, and sudo's job is now done once it runs cat /dev/null.

That means that the > is running as your user, not under sudo. Your user doesn't have permission to write to /var/log/syslog, so this will fail.

You need some way to run the entire line cat /dev/null > /var/log/syslog under sudo. Well, > isn't a command or anything. It's something the shell handles, so you need to have a shell handle that redirection symbol properly. You can do that with sh's -c option: sh -c 'cat /dev/null > /var/log/syslog'.

Now that you have everything together as one command, you can have sudo run the entire thing:

sudo sh -c 'cat /dev/null > /var/log/syslog'
  • No command is needed, the > is enough. The OP just got an error but did truncate the target file, see my answer. – terdon Mar 18 '14 at 20:25
  • Agreed. Except that "sudo allows a permitted user to execute a command as the superuser or another user, as specified by the security policy." – Elliott Frisch Mar 18 '14 at 20:28
  • True, but irrelevant. The OP would get the same error with or without sudo, it comes from bash, not from sudo. – terdon Mar 18 '14 at 20:32
  • The first command worked for me with root login. – We are Borg Oct 28 '15 at 8:47

The command you are thinking of is probably

> /var/log/syslog

Nothing else is needed. In bash and other shells, the > will immediately truncate the file, emptying it. However, when you run this:

sudo /dev/null > /var/log/syslog

The system is attempting to run /dev/null as a command and you will get this error:

sudo: /dev/null: command not found

Note, however, that despite this, /var/log/syslog has actually been emptied because, as I said above, the > is enough, no command is necessary.

truncate -s 0 /var/log/syslog

working for me on 18.04. Got it from here:

https://ubuntuforums.org/showthread.php?t=2191156

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.