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.


1 Answer 1


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 ~'
  • How to do this with -u? I tried sudo -u otheruser bash -c 'ls ~', but it still lists my own home directory.
    – not2savvy
    Commented May 16, 2023 at 8:56
  • @not2savvy -u “just works” for me, I’m not sure what might be different in your case. Commented May 16, 2023 at 14:12
  • I found out that it does work in exactly the same way on every *nix flavor. On macOS, which is BSD Unix based, the command requires option -i (interactive shell) to be added, which I suppose causes the shell to establish the destination user environment. This also works under Ubuntu, so I propose that the suggested solution be sudo bash -i -c 'ls ~'
    – not2savvy
    Commented May 16, 2023 at 19:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .