1
sudo date > output.txt
bash: output.txt: Permission denied

I want to write log message into file, but the permission denied even I add prefix sudo, But when I tried after making output.txt file and changing permission to 755, It works well.

How can I write log meesage without making file and changing permission?

simply like sudo date > output.txt --chmod 755 ?

ton1
  • 125

1 Answers1

3
date | sudo tee output.txt > /dev/null

This works because tee opens the output.txt and it is running as root. The > /dev/null is just to throw away the extra copy that tee would send to stdout.

The reason why sudo date > output.txt doesn't work is that the output redirection (the > output.txt) is done before the sudo date is started, and so runs with the current access rights.

A different approach would be to change the permissions on the current directory to allow the current user to create files. Doing this would mean that date > output.txt could work without needing sudo.

icarus
  • 17,920