0

I've tried every possible combination to get this bash script working. It's part of a larger script, and it basically prompts for a username (to check if it exists) and returns the appropriate response:

#! /bin/bash
# Script to see if User exists

clear
echo -n "Enter user to check: "
read $uzer

grep -c '^${uzer}:' /etc/passwd

if [ $? -eq 0 ]; then
  echo "User does exist :)"
else
  echo "No such user"
fi

In terminal the following works fine:

grep -c '^devuser1:' /etc/passwd
RETURNS: 1
grep -c '^devuser1234:' /etc/passwd
RETURNS: 0

I've tried many combinations of passing the read variable into '^${uzer}:' with no joy. Any ideas what else I can try?

1
  • read $uzer should be read uzer Apr 29, 2013 at 14:25

2 Answers 2

3

-c means that you want to know the number of times this user is in /etc/passwd, while $? is the exit code. Those are differents, since the number of times is printed on stdout. Use $() for getting stdout into a variable

Second problem: all your variables, like $uzer will not be substituted with their values when in single quotes. Use double quotes.

number=$(grep -c "^${uzer}:" /etc/passwd)
if [ $number -gt 0 ]; then
  echo "User does exist :)"
else
  echo "No such user"
fi
8
  • Thanks for your reply! However, I get the following error: Enter user to check: devuser1 ./userexist.sh: line 8: =0: command not found ./userexist.sh: line 10: [: -eq: unary operator expected No such user
    – maGz
    Apr 29, 2013 at 13:58
  • sorry, can't do newlines in comments!
    – maGz
    Apr 29, 2013 at 13:59
  • right. I already corrected my answer. Please use number instead of $number in the assignment.
    – eppesuig
    Apr 29, 2013 at 13:59
  • 1
    there is an error in the read command: it must be read uzer rather than read $uzer.
    – Uwe
    Apr 29, 2013 at 14:04
  • 1
    Bourne shell and bash distinguish between a variable and its current value. If you want the current value of variable A, it's $A; if you want the container rather than what's inside (i.e., in assignments A=... and read A) the $ is missing.
    – Uwe
    Apr 29, 2013 at 14:10
2

You need grep -q. If you don't distinguish between more exit codes than "0" and "other" there is no need to seperate grep and if:

if grep -q "^${uzer}:" /etc/passwd; then
  echo "User does exist :)"
else
  echo "No such user"
fi
3
  • The single quotes around ^${uzer}: must be replaced by double quotes, otherwise the variable ${uzer} is not expanded.
    – Uwe
    Apr 29, 2013 at 14:02
  • @Uwe How embarrassing. I just copied the code and was looking at the other problem only... Apr 29, 2013 at 14:05
  • Hi Hauke. Thanks anyway for your response. The answer from eppesuig above worked like a charm. I did something similar to this before, and the error I got was "...too many arguments..."
    – maGz
    Apr 29, 2013 at 14:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .