[英]how to find the user is logged in as root in Linux using bash script?
這是一個簡單的函數,腳本可以使用該函數來查找用戶是否以root用戶身份登錄。
do_check_user(){
id | grep root 1>/dev/null 2>&1
if test "$?" != "0"
then
echo ""
echo " Invalid login, Please logon as root and try again!"
exit 0
fi
}
我不完全了解此功能的工作原理。 我嘗試了一些在線搜索,以查找實現方式的點點滴滴。 但我仍然不清楚。
特別是這些行:
id | grep root 1>/dev/null 2>&1
if test "$?" != "0"
我試圖一步一步地做。 但是我得到了錯誤
id | grep root 1
grep: 1: No such file or directory
如果您能向我解釋這種語法及其作用,那將非常有幫助
謝謝
您只需使用whoami
命令即可。
#!/bin/bashyou
if [[ $(whoami) == 'root' ]] ; then
echo "it's root"
fi
僅針對bash進行編輯 :您還可以使用$ EUID變量來引用用戶標識符,因此在根情況下,它等於0
(($EUID == 0)) && echo 'root'
id
打印真實有效的用戶和組ID
grep
在id的輸出中搜索root
1>/dev/null 2>&1
將stdout/stderror
發送到/dev/null
; 因此,您將不會看到輸出1>/dev/null
僅將stdout to /dev/null
發送stdout to /dev/null
if test "$?" != "0"
if test "$?" != "0"
檢查最后執行的命令grep
,如果為0
表示成功,如果不為0
則將得到消息。
在bash
,您可以僅測試$UID
:
if ((UID==0)); then
# I'm root
fi
試試whoami
:
do_check_user() { test $(whoami) = root; }
我看到這里有很多人使用操作數==和!=比較真假位,我建議對於==不使用任何表示真實的值,而只使用! 為假。
例如
if ((UID)); then echo 'This means the test is Boolean TRUE and the user is not root'
if ((!UID)); then echo 'This means the test is Boolean FALSE and the user is root'
或者將數字變量與布爾值TRUE或FALSE進行比較
if [[$a]]; then echo "If the variable 'a' is a 1 then it's Boolean TRUE"
if [[!$a]]; then echo "If the variable 'a' is a 0 (zero) then it's Boolean FALSE"
當比較TRUE或FALSE時,不需要==和!=操作,這也節省了一些按鍵。
使用whoami
:
if [ `whoami` == "root" ] ; then
echo "root"
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.