-3

When I'm logged in as username, why does

sudo ls ~

show me the contents of /home/username rather than /root? I thought that sudo executes a command as root, in which case ~ would represent /root.

more explanation:

Additionally, if I run the su command, and then run ls ~, I am shown contents of /root. So I thought doing that was equivalent to sudo ls ~.

As another example, some commands with a --user flag will interpret the user to be root when run as sudo. For example, pip install --user packagename will install to a directory within /home/username, while sudo pip install --user packagename will install to a directory within /root. Note that it is not advised to run the last command, I'm just using it to show the functionality I'm describing.

7

The shell expands ~ before running sudo; you can see this in action with set -x:

$ set -x
$ sudo ls ~
+ sudo ls /home/skitt

which shows that the command actually run already has the home directory expanded, using the current user at the time of the expansion.

To see the target user’s home directory, you have to defer the tilde expansion:

sudo bash -c 'ls ~'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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