mitnk
Posts: 2
Joined: Mon Dec 28, 2015 1:57 am

sudo extends ~ to /root

Sat Jan 02, 2016 5:00 pm

Hi everyone,

I am write some bash code like this:

Code: Select all

echo ${XYZ:-~/.vimrc}
saved as foo.sh and I run it with:

Code: Select all

sudo ./foo.sh
When I run at Raspbian, I got:

Code: Select all

/root/.vimrc
(What I expected was: /home/pi/.vimrc)

But at other OS (Ubuntu and OS X), I got this (mitnk is my username):

Code: Select all

/home/mitnk/.vimrc
The OS info:

PRETTY_NAME="Raspbian GNU/Linux 8 (jessie)"
NAME="Raspbian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"

Can anyone explain why it's not `/home/pi/.vimrc`? Thanks.

disorientedp
Posts: 58
Joined: Mon Aug 03, 2015 11:43 pm

Re: sudo extends ~ to /root

Sun Jan 03, 2016 12:51 am

Try ~pi/otherstuff instead of ~/otherstuff.

disorientedp
Posts: 58
Joined: Mon Aug 03, 2015 11:43 pm

Re: sudo extends ~ to /root

Sun Jan 03, 2016 12:53 am

The root home directory (which is what commands are run through with sudo) is different than other home directories.

QuietZone
Posts: 89
Joined: Sat Dec 05, 2015 7:13 pm

Re: sudo extends ~ to /root

Sun Jan 03, 2016 2:27 am

The real answer to this question is that it is, as you've observed, kind of a dark corner.

Like you, I've seen it behave differently on different versions of Unix/different distros of Linux, etc. You just have to accept it.

The exact semantics of "su" have never really been nailed down.
"If you haven't got anything nice to say about anybody come sit next to me." — Alice Roosevelt Longworth

mitnk
Posts: 2
Joined: Mon Dec 28, 2015 1:57 am

Re: sudo extends ~ to /root

Sun Jan 03, 2016 6:45 am

Thanks @disorientedp and @QuietZone for the tips / informations.

User avatar
jojopi
Posts: 3271
Joined: Tue Oct 11, 2011 8:38 pm

Re: sudo extends ~ to /root

Sun Jan 03, 2016 7:03 am

To preserve ~/ in non-login sessions started via sudo, add to /etc/sudoers using sudo visudo:

Code: Select all

Defaults        env_keep += "HOME"
I personally like this configuration, but some regard it as having security implications. Also it definitely increases the risk that configuration files under /home/pi/ will be created with root ownership, so you should be comfortable with managing permissions before enabling it.

Return to “Raspberry Pi OS”