1

I want to check if the user running the script is root or not before running. But it doesn't seem to work. I'm currently logged in as root, but its something wrong with the syntax I think.

if[[ $EUID -ne 0 ]];
then
 echo "Sorry, you are not root."
 exit 1
else
 echo "You are root, script will continue."
fi
romeo
  • 191
  • 2
  • 14

2 Answers2

4

You need a space between if and [.

user3553031
  • 5,990
  • 1
  • 20
  • 40
1

Why not simething like:

usrname=$(whoami)
if [ $usrname = "root" ]
echo "Sorry, you are not root."
 exit 1
else
  echo "You are root, script will continue."
fi

Although I think the problem is merely your syntax with the if statement:

  • Why double brackets
  • Why a ; after the if?
  • A space between if and [, thus if [

bash is very sensitive to syntax. For instance spaces between the assignment operator (=) are not allowed either.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • When I find that user is not my desired user, instead of exit, how can I run the rest of the script as my desired user? Please look at https://stackoverflow.com/questions/67646925/how-to-check-user-inside-bash-script-and-run-as-another-user – Kalyanam Rajashree May 22 '21 at 07:03