Reputation: 31272
Here is a simple function that our script uses to find if user is logged in as 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
}
I do not completely understand how this function works. I tried some searching online to find bits and parts of how it is implemented. but it is still not clear to me.
Especially these lines:
id | grep root 1>/dev/null 2>&1
if test "$?" != "0"
I tried doing step by step. But I get error
id | grep root 1
grep: 1: No such file or directory
if you could explain me this syntax and what it is doing, it will be very helpful
Thanks
Upvotes: 0
Views: 1163
Reputation: 11
I see a lot of people here are using operands == and != to compare true and false bits, I would suggest using nothing for the == to represent true and just using ! for false.
EG
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'
Or if comparing a numerical variable to Boolean TRUE or 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"
When comparing TRUE or FALSE the operations == and != is not needed, this saves a few key strokes too.
Upvotes: 1
Reputation: 9709
You simply can use whoami
command.
#!/bin/bashyou
if [[ $(whoami) == 'root' ]] ; then
echo "it's root"
fi
EDIT Only for bash:
you can also you $EUID variable which refers to user identifier, so in root case it equals 0
(($EUID == 0)) && echo 'root'
Upvotes: 1
Reputation: 1197
id
- print real and effective user and group IDs
grep
searches through the output of id for root
1>/dev/null 2>&1
sends stdout/stderror
to /dev/null
; therefore you won't see the output 1>/dev/null
sends only stdout to /dev/null
if test "$?" != "0"
checks the status of the last executed command which is grep
, if it is 0
means sucessful and if it is not 0
, you will get the messages.
Upvotes: 2