A simple shell script to check whether user is root
In many case inside your shell script you need to check whether the user who runs the script is root or not because based on the user you might need to take necessary action inside your shell script.
Following shell script might help you in this case.
Way 01: With system variable $LOGNAME
As echo $LOGNAME show the currently logged in user show we can use this variable to determine whether it is root user.
1)create script
# vi test_root.sh
if [[ $LOGNAME = "root" ]]
then
echo "You are root user"
else
echo "You are $LOGNAME user"
fi
2)Grant execute permission.
# chmod +x test_root.sh
3)Test it by running as root.
# whoami
root
# ./test_root.sh
You are root user
4)Test it by running as oracle user.
# su - oracle
$ whoami
oracle
$ ./test_root.sh
You are oracle user
Way 02: As system variable $UID:
As system variable $UID for root user is zero so we can use that in order to determine whether user is root.
1)create script
# vi test_root2.sh
if [[ $UID = "0" ]]
then
echo "You are root user"
else
echo "You are not root user"
fi
2)Give execute permission.
# chmod +x test_root2.sh
3)Test it by running as root user.
# ./test_root2.sh
You are root user
Way 03: With the command whoami
With the command whoami you can check the user who is logged in. So you can use that in your script.
1)Create script
# vi test_root3.sh
if [ `whoami` = "root" ]
then
echo "You have logged on as root"
else
echo "You are not root user"
fi
2)Grant execute permission.
# chmod +x test_root3.sh
3)Test the script by running it.
# ./test_root3.sh
You have logged on as root
Following shell script might help you in this case.
Way 01: With system variable $LOGNAME
As echo $LOGNAME show the currently logged in user show we can use this variable to determine whether it is root user.
1)create script
# vi test_root.sh
if [[ $LOGNAME = "root" ]]
then
echo "You are root user"
else
echo "You are $LOGNAME user"
fi
2)Grant execute permission.
# chmod +x test_root.sh
3)Test it by running as root.
# whoami
root
# ./test_root.sh
You are root user
4)Test it by running as oracle user.
# su - oracle
$ whoami
oracle
$ ./test_root.sh
You are oracle user
Way 02: As system variable $UID:
As system variable $UID for root user is zero so we can use that in order to determine whether user is root.
1)create script
# vi test_root2.sh
if [[ $UID = "0" ]]
then
echo "You are root user"
else
echo "You are not root user"
fi
2)Give execute permission.
# chmod +x test_root2.sh
3)Test it by running as root user.
# ./test_root2.sh
You are root user
Way 03: With the command whoami
With the command whoami you can check the user who is logged in. So you can use that in your script.
1)Create script
# vi test_root3.sh
if [ `whoami` = "root" ]
then
echo "You have logged on as root"
else
echo "You are not root user"
fi
2)Grant execute permission.
# chmod +x test_root3.sh
3)Test the script by running it.
# ./test_root3.sh
You have logged on as root
Comments
Post a Comment