I made this bash function to detect if the user running is actually logged in as root user and not using sudo by checking the uid + home directory of the user executing the command:
#!/bin/bash
set -x
function check_root(){
home=`sh -c 'cd ~/ && pwd'`
if [ "$home" != "/root" ] || [ "$(id -u)" != "0" ]; then
echo -e "This script can only be executed by the root user, not with sudo elevation"
exit 1
fi
}
check_root
When i run it as a regular user (uid 1000) it works as expected:
++ check_root
+++ sh -c 'cd ~/ && pwd'
++ home=/home/jake
++ '[' /home/jake '!=' /root ']'
++ echo -e 'This script can only be executed by the root user, not with sudo elevation'
This script can only be executed by the root user, not with sudo elevation
++ exit 1
When i run it as root it also works as expected:
++ check_root
+++ sh -c 'cd ~/ && pwd'
++ home=/root
++ '[' /root '!=' /root ']'
+++ id -u
++ '[' 0 '!=' 0 ']'
But when i run it as regular user (uid 1000) with sudo elevation i get this:
./check_root.sh: 4: ./check_root.sh: Syntax error: "(" unexpected
System info:
Linux jake 3.11.0-26-generic #45~precise1-Ubuntu SMP Tue Jul 15 04:02:35 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
bash --version GNU bash, versie 4.2.25(1)-release (x86_64-pc-linux-gnu)
function check_root () {
instead? Does it appear if you run it as normal user withenv - ./check_root.sh
?bash
. On many systems, for example,dash
is the default shell and it would give that exact error message. The details of how you invoke the script would be important here.function
keyword at the beginning.$home
rather than$HOME
or, better, the output of$(whoami)
?<check_root.sh head -n 1 | od -t x1
?