[英]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.