Search code examples
bashescapingcommand-substitutiontilde-expansionvariable-substitution

combining tilde expansion with variable substitution in bash


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?


Solution

  • 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.