首页 > 解决方案 > bash 有没有办法在没有 $HOME 变量的情况下知道主目录

问题描述

我发现 bash,即使我取消设置 HOME、USER、LOGNAME 环境变量和 write cd ~,仍然知道 HOME 目录的路径。这是怎么发生的?

标签: cshellenvironment-variables

解决方案


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

推荐阅读