How to find a user's home directory on linux or unix?

后端 未结 13 625
时光说笑
时光说笑 2020-12-23 19:57

How do I find the home directory of an arbitrary user from within Grails? On Linux it\'s often /home/user. However, on some OS\'s, like OpenSolaris for example, the path i

13条回答
  •  感情败类
    2020-12-23 20:16

    If your are trying to do this for a user name that you cannot hard code, it can be challenging. Sure echo ~rbronosky would tell you the path to my home dir /home/rbronosky, but what if rbronosky is in a variable? If you do name=rbronosky; echo ~$name you get ~rbronosky

    Here is a real world case and the solution:

    You have a script that the user has to run via sudo. The script has to access the user's home folder. You can't reference ~/.ssh or else it will expand to /root/.ssh. Instead you do:

    # Up near the top of your script add
    export HOME=$(bash <<< "echo ~${SUDO_USER:-}")
    # Then you can use $HOME like you would expect
    cat rsa_key.pub >> $HOME/.ssh/authorized_keys
    

    The beauty of it is that if the script is not run as sudo then $SUDO_USER is empty, so it's basically the same thing as doing "echo ~". It still works as you' expect.

    If you use set -o nounset, which you should be using, the variable reference ${SUDO_USER:-} will default to blank, where $SUDO_USER or ${SUDO_USER} would give an error (because it is unset) if not run via sudo.

提交回复
热议问题