2

In a standard bash shell, I was trying to cat a file from several users' home directories which are on a root-squashed NFS mount so I couldn't just read them as root :

sudo -u userA cat ~userA/blah

.. works fine. However trying this in a loop doesn't work :

for x in userA userB userC; do sudo -u $x cat ~$x/blah; done

.. doesn't work :

cat: ~userA/blah: Permission denied
cat: ~userB/blah: Permission denied
cat: ~userC/blah: Permission denied

Now there's other ways to achieve the desired result but what I'm trying to understand is why the for loop doesn't work

Gaspode
  • 85

1 Answers1

1

I think this part is probably not working because of the order of operations. Tilde expansion happens before parameter expansion, so you are actually trying to a find a file literally named, for example, ~userA/blah not a file named blah in userA's home directory.

You could invoke another shell to get the next round of expansion like

sudo -u "$x" sh -c "cat ~/blah"

and you shouldn't need to specify the username in the path since you'll already be that user and ~ should be their home dir anyway

Eric Renouf
  • 949
  • 9
  • 20
  • Ah, that does seem to be the issue. Simply changing the command to....
    for x in userA userB userC; do sudo -u $x cat /home/$x/blah; done ....is enough to fix it.
    – Gaspode Aug 23 '16 at 08:27