美文网首页
如何通过代码准确获取用户home目录

如何通过代码准确获取用户home目录

作者: fstMoon | 来源:发表于2019-01-08 21:12 被阅读0次

    https://github.com/golang/go/issues/26463

    1. $HOME should be used, if available, as user's home directory. Quoting http://man7.org/linux/man-pages/man3/getpwuid_r.3.html:

    The pw_dir field contains the name of the initial working directory
    of the user. Login programs use the value of this field to
    initialize the HOME environment variable for the login shell. An
    application that wants to determine its user's home directory should
    inspect the value of HOME (rather than the value
    getpwuid(getuid())->pw_dir) since this allows the user to modify
    their notion of "the home directory" during a login session.

    1. Tilde Expansion
      https://stackoverflow.com/questions/20504662/how-to-get-home-directory-of-different-user-in-bash-script

    In that case, the simplest solution is to use tilde expansion with the username of interest, combined with eval (which is needed, because the username must be given as an unquoted literal in order for tilde expansion to work):

    eval echo "~$different_user"    # prints $different_user's home dir.
    

    相关文章

      网友评论

          本文标题:如何通过代码准确获取用户home目录

          本文链接:https://www.haomeiwen.com/subject/aqfirqtx.html