Mac 系统下 Emacs 获取系统变量问题

在学习prelude的配置代码,他的代码里面有一个获取系统用户的一段代码,如下:

(defvar current-user
  (getenv
   (if (equal system-type 'windows-nt) "USERNAME" "USER")))

(message "Master %s!" current-user)

我理解是,当系统类型是 Windows 时获取用户信息,然后message出来。

我修改成:

(defvar current-user
  (getenv
   (if (equal system-type 'darwin) "USER")))

(message "Master %s!" current-user)

printenv 命令查看了下,是有"USER",并用 (getenv "USER") 试了下,能够显示正常,但是运行上述代码就会显示 nil,请问下该如何修改,谢谢。

代码没问题,我在 Mac 上运行正常。可以尝试 emacs -Q ,再测试这段代码,应该是其他地方出错了。

测试的时候用 setq 替代 defvar,我估计是因为之前运行过 (defvar current-user (getenv (if (equal system-type 'windows-nt) “USERNAME” “USER”))) 已经给 current-user 绑定了 nil,defvar 对已经绑定的变量,就算是 nil,也不会生效。

1 个赞

但是为什么运行这个

(defvar current-user (getenv (if (equal system-type 'windows-nt) “USERNAME” “USER”)))

会是nil 呢,这个不是应该也是获取 USER么?附加一句,只有一个分支的时候,用 when而不是if.

1 个赞

估计是别的什么地方设置过了。。

所以建议改成:

(setq current-user (getenv (when (equal system-type 'darwin) “USER”)))

谢谢各位,知道为什么了,如@LdBeth所说,“之前运行过 (defvar current-user (getenv (if (equal system-type 'windows-nt) “USERNAME” “USER”))) 已经给 current-user 绑定了 nil,defvar 对已经绑定的变量,就算是 nil,也不会生效。” 我一开始运行过 (defvar current-user (getenv (if (equal system-type 'windows-nt) “USERNAME” “USER”))) ,后面不管怎么改,都不行。mac中没有“USERNAME”,只有“USER”。重启过mac后,再运行,就👌了。 再次谢谢各位。