c - bash 有没有办法在没有 $HOME 变量的情况下知道主目录
问题描述
我发现 bash,即使我取消设置 HOME、USER、LOGNAME 环境变量和 write cd ~
,仍然知道 HOME 目录的路径。这是怎么发生的?
解决方案
C 代码可以调用getpwnaw
, getpwuid
,之类的函数getpwent
来获取有关用户的信息。
在 Bash 的源代码中lib/tilde/shell.c
,请参见第 69 行:
59 char *
60 get_home_dir (void)
61 {
62 static char *home_dir = (char *)NULL;
63 struct passwd *entry;
64
65 if (home_dir)
66 return (home_dir);
67
68 #if defined (HAVE_GETPWUID)
69 entry = getpwuid (getuid ());
70 if (entry)
71 home_dir = savestring (entry->pw_dir);
72 #endif
73
74 #if defined (HAVE_GETPWENT)
75 endpwent (); /* some systems need this */
76 #endif
77
78 return (home_dir);
79 }
在 中lib/tilde/tilde.c
,参见第 386 行:
335 char *
336 tilde_expand_word (const char *filename)
337 {
338 char *dirname, *expansion, *username;
339 int user_len;
340 struct passwd *user_entry;
...
384 dirname = (char *)NULL;
385 #if defined (HAVE_GETPWNAM)
386 user_entry = getpwnam (username);
387 #else
388 user_entry = 0;
389 #endif
...
推荐阅读
- selenium - 如果 Selenium webdriver 中的页面上不存在元素,如何获取 false
- docker-compose - 将 WP-CLI 容器添加到 LEMP 堆栈
- php - 如何像谷歌一样跨网站登录?
- android - Android:杀死一个活动
- html - 您如何使用 Chrome 开发人员工具找出网页上出现空白的原因?
- r - 如何在R中具有水平填充区域图
- javascript - jquery:发票中所有输入字段的总和
- lazarus - Lazarus:堆叠图像,绘画顺序
- javascript - 遍历嵌套数组,按索引对对象进行分组
- python-3.x - 从 csv 获取数据并将相应的列放入字典