[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命令。希望本文能對你有所幫助。

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