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

fstMoon · · 883 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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.

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:fstMoon

查看原文:如何通过代码准确获取用户home目录

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

883 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传