0

I just confused to create file with sudo command. As i know, sudo command is commonly used for root privilege(by default) and when i created files using command below:

sudo cat > root.txt

And i saw the user, it still regular username not root. How that can be happen? and how to create files owned by root without changing user to root?

Zozzizzez
  • 455
  • 1
  • 6
  • 12
  • No not root privileges. Admin privileges. root is just another admin. " and how to create files owned by root without changing user to root?" you do realize this is 1 way? you can then do nothing with the file unless "others" has executable rights on the file? – Rinzwind Sep 29 '20 at 12:46
  • 2
    It's because your unprivileged shell creates `root.txt`, then runs `cat` with `sudo`. See related [How to solve “permission denied” when using sudo with redirection in Bash?](https://askubuntu.com/questions/230476/how-to-solve-permission-denied-when-using-sudo-with-redirection-in-bash) – steeldriver Sep 29 '20 at 12:49

2 Answers2

4

Redirection is 'outside' of sudo in your example. Try

sudo bash -c "cat > root.txt"
sudodus
  • 45,126
  • 5
  • 87
  • 151
2

Stream redirection (> file) takes place in the parent process (running as $USER) before the command (sudo) even begins.

You can either use a different command:

sudo tee root.txt

or, afterwards, change the ownership of the file:

sudo chown root:root root.txt 
  
waltinator
  • 35,099
  • 19
  • 57
  • 93