2

Say I'm running bash as root, and I want to chown the home directory of a user ada. Say also that ada is stored in a variable called $USER (because I'm doing this from a script).

When I tried the following,

chown -R $USER:$USER ~$USER

the shell performed tilde expansion first, so it tried to chown /home/root/ada, rather than /home/ada.

Is there some way to do it with nested substitions and proper escaping?

Chris Middleton
  • 4,734
  • 1
  • 25
  • 54

2 Answers2

3

Tilde expansion is tricky and doesn't work with variables like that.

One way is to use eval:

chown -R $USER:$USER $(eval echo ~"$USER")

But make sure your USER variable is not coming from untrusted sources.

anubhava
  • 664,788
  • 59
  • 469
  • 547
0

I wound up here because I had the sort of problem.

I came up with:

chown -R $USER:$USER $(getent passwd $USER | awk -F: '{print $6}')

But I like anubhava's (slightly scary) eval based suggestion better.

Thanks!