简体   繁体   中英

how to find the user is logged in as root in Linux using bash script?

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

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'
  1. id - print real and effective user and group IDs

  2. grep searches through the output of id for root

  3. 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

  4. if test "$?" != "0" 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.

In bash , you can just test $UID :

if ((UID==0)); then
   # I'm root
fi

试试whoami

do_check_user() { test $(whoami) = root; }

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.

Use whoami :

if [ `whoami` == "root" ] ; then
    echo "root"
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM