PDA

View Full Version : bash scripting



frustphil
September 28th, 2009, 01:24 AM
Out of curiosity, I am studying it. =)
I am having trouble figuring out what's wrong with this script.


#!/bin/bash
#This a script that identifies a user whether he/she is a normal, system,
#or a root user.

echo -n "Please enter your username: "
read username

if sudo grep -q $username /etc/passwd
then
id=$(sudo id -u $username)
declare -i user_id
user_id=$id

if [ $user_id -ge 500 ]
then
echo "$username, you are a noraml user"
elif [ $user_id -eq 0 ]
echo "$username, you are a root user"
else
echo "$username, you are a system user"
fi
else echo "Sorry, you're not a valid user!"
fi
if I run it, the shell gives me this error:

Please enter your username: frustphil
./identify_user.sh: line 16: syntax error near unexpected token `else'
./identify_user.sh: line 16: ` else '
Any idea what's wrong?
Thanks...=)

falconindy
September 28th, 2009, 02:03 AM
Your elif needs a then.

You also don't need to be sudo to use `id`.

frustphil
September 28th, 2009, 02:12 AM
Your elif needs a then.

You also don't need to be sudo to use `id`.

So it's the tutorial I followed.. Thanks =)

phrostbyte
September 28th, 2009, 02:30 AM
The current shell's UID is in the variable $EUID

Eg:



if [[ $EUID -ne 0 ]]; then
echo "Error: This script must be run as a superuser. Did you prefix with sudo or are you root?"
echo
exit 1
fi

lswb
September 28th, 2009, 03:33 AM
Also ubuntu and debian start numbering for regular users at 1000, not 500.

diesch
September 28th, 2009, 05:36 PM
You don't need sudo to access /etc/passwd either (passwords are stored in /etc/shadow this days).


grep -q $username /etc/passwd doesn't do what you want here as it finds not only full user names but partial usernames (like "roo") and other text from /etc/passwd (like "bash"), too.
Either use

grep "^${username}:" /etc/passwd or
getent passwd "$username".

clivelr
September 30th, 2009, 05:14 AM
You forgot the "then" after the elif statement.



elif [ $user_id -eq 0 ]
then
echo "$username, you are a root user"

else

frustphil
October 2nd, 2009, 05:02 AM
thanks to all =)