[Linux] whoami命令与其继任者的id命令

前言

笔者一度很喜欢使用(入IT坑之时搜索所知)的whoami命令其实是已经过时的命令。所以对其做了一番调查,并写下本文介绍其后任者。

参考

  1. whoami - wikipedia
  2. id - POSIX 2018 edition
  3. POSIX - wikipedia

正文

笔者将在本节介绍whoami命令与其继任者id命令。

whoami命令


在日常工作中,笔者会经常需要连接到远端Linux服务器,对其做设置和部署与错误排查。而通常在作业的确认环节往往需要打印当前用户的ID,而whoami就是在Unix及类似系统里用于打印当前用户ID的命令。

Last login: Thu Nov 28 01:09:19 on ttys000
humao:~ toranekojp$ whoami
toranekojp
humao:~ toranekojp$ sudo su - humaoer // 切换用户
Password:
➜  ~ whoami
humaoer
➜  ~ exit
humao:~ toranekojp$ whoami
toranekojp
humao:~ toranekojp$ 

而实际上,这个命令在笔者查看其man page的时候发现,已经过时并且有了POSIX标准下的继任者id命令。

DESCRIPTION
     The whoami utility has been obsoleted by the id(1) utility, and is
     equivalent to ``id -un''.  The command ``id -p'' is suggested for
     normal interactive use.

     The whoami utility displays your effective user ID as a name.

id 命令


whoami的替代者的id命令,其基础功能是由POSIX标准所规定,而实现则是由各家操作系统供应商完成。
因POSIX标准是IEEE标准里的一员,所以作为标准化的产物,id命令比whoami命令更加规范,并且只要支持POSIX标准的操作系统,就会有id命令。所以在日常作业中,用已经标准化的id命令是更加推荐的。

id 命令的使用例


本节将根据POSIX标准页的定义,简单列举id命令所支持的option和其使用效果。需要注意man page所看到id命令的文档的可能是各个操作系统供应商扩展后的结果。本文不会在其基础上做讨论。

OPTIONS
	The id utility shall conform to XBD Utility Syntax Guidelines .
	The following options shall be supported:
	-G
		Output all different group IDs (effective, real, and supplementary) only, using the 		format "%u\n". If there is more than one distinct group affiliation, output each such affiliation, using the format " %u", before the <newline> is output.
	-g
		Output only the effective group ID, using the format "%u\n".
	-n
		Output the name in the format "%s" instead of the numeric ID using the format "%u".
	-r
		Output the real ID instead of the effective ID.
	-u
		Output only the effective user ID, using the format "%u\n".

1. id -un: 打印当前用户名

whoami的继任命令,在其的man page里有记载。

humao:~ toranekojp$ id -un
toranekojp
humao:~ toranekojp$ whoami
toranekojp

2. id -Gn: 打印所有用户组名

groups的继任命令,在其的man page里有记载。

humao:~ toranekojp$ id -G
20 503 12 61 79 80 ... // 由笔者省略
humao:~ toranekojp$ id -Gn
staff ME everyone localaccounts _appserverusr admin ... // 由笔者省略
humao:~ toranekojp$ groups
staff ME everyone localaccounts _appserverusr admin ... // 由笔者省略

3. id -gn: 打印当前用户组名

笔者暂时没有找到其前任。

humao:~ toranekojp$ id -gn
staff
humao:~ toranekojp$ id -g // 打印其用户组的ID
20 

题外话:POSIX标准


POSIX,全称Portable Operating System Interface,中译可移植操作系统接口。是IEEE定义的一组操作系统接口标准。该标准可以在IEEE Std 1003可以购买。然而IEEE一直以来就比较贵,笔者通常做参考所用的是OpenGroup官网上所公开的POSIX标准的文档。
根据POSIX的维基百科所记载

POSIX - certified
macOS(since 10.5 Leopard) , Solaris


Mostly POSIX-compliant
Android (Avaliable through Android NDK), Linux (most distributions), OpenBSD, OpenSolaris

macOS从10.5版之后就已经全面通过POSIX认证,POSIX的接口都被macOS所支持。
而Linux大部分的构建则是没有通过POSIX认证的,但可以认为已经很接近POSIX的标准,可能有少部分POSIX接口不被支持。

结语


IT领域,发展迅速,就算是标准也不会一成不变。知道自己的知识已经过时然后积极拥抱变化是对自己或是对企业都是有积极意义的。笔者在今后的标准作业手顺书里也将改用id命令,而不是继续沿用whoami命令。希望本文能对你有所帮助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章