Shell – Who is file owner if the file is created using sudo command

io-redirectionpermissionsshellsudo

I logged in using my username ravbholua:

ravbholua@ravbholua-Aspire-5315:~$ echo $LOGNAME
ravbholua

I create file named a1:

ravbholua@ravbholua-Aspire-5315:~$ echo>a1
ravbholua@ravbholua-Aspire-5315:~$ ll a1
-rw-rw-r-- 1 ravbholua ravbholua 1 Oct  8 09:57 a1

As expected the above file has me (ravbholua) as owner.

Next I create a2 using sudo with echo command:

ravbholua@ravbholua-Aspire-5315:~$ sudo echo>a2
ravbholua@ravbholua-Aspire-5315:~$ ll a2
-rw-rw-r-- 1 ravbholua ravbholua 1 Oct  8 09:57 a2

The owner is me only, i.e. ravbholua.

Now I create a3 using sudo again but with vim command:

ravbholua@ravbholua-Aspire-5315:~$ sudo vim a3
ravbholua@ravbholua-Aspire-5315:~$ ll a3
-rw-r--r-- 1 root root 10 Oct  8 09:57 a3

Oh! how come the owner changes now. It's not me but root.
Why such variation with echo and vim!
It's a surprise that with change of commands how can the owner of the created file changes.

Best Answer

The second example runs echo under sudo, but the redirection happens under the original shell.

sudo bash -c "echo > a4"
Related Question