Reputation: 13
I have been trying to make a shell script in bash that will display the following:
You are the super user (When I run the script as root). You are the user: "user" (When I run the script as a user).
#!/bin/bash/
if { whoami | grep "root" }; then
echo $USER1
else
echo $USER2
fi
I keep recieving these syntax error messages:
script.sh: line 2: syntax error near unexpected token `then'
script.sh: line 2: `if { whoami | grep "root" }; then'
Could someone help me out?
Upvotes: 0
Views: 1920
Reputation: 488
pay attention with your first line, the correct syntax for she-bang is:
#!/bin/bash
everything you put there, is the interpreter of your script, you can also put something like #!/usr/bin/python
for python scripts, but your question is about the if statement, so you can do this in two ways in shell script using
if [ test ] ; then doSomething(); fi
or
if (( test )) ; then doSomething(); fi
so to answer your question basically you need to do this
#!/bin/bash
if [ `id -u` -eq 0 ] ; then
echo "you are root sir";
else
echo "you are a normal user"
fi
if (( "$USER" = "root" )); then
echo "you are root sir";
else
echo "you are a normal user"
fi
note that you could use a command using `cmd`
or $(cmd)
and compare using -eq
(equal) or =
(same), hope this help you :-)
Upvotes: 0
Reputation: 927
userType="$(whoami)"
if [ "$userType" = "root" ]; then
echo "$USER1"
else
echo "$USER2"
fi
Upvotes: 1
Reputation: 799420
If braces are used to chain commands then the last command must have a command separator after it.
{ foo ; bar ; }
Upvotes: 2