4

I'm making a script that add an user, deletes an user and change password of an user passed as parameter ($1). I want to check if the user exists, so I can control this better. I know this question have been asked a lot of times, I've been googling this before, but really, these solutions didn't work for me, I don't know which is my mistake, so sorry.

This is my code:

#!/bin/bash
existe=$(grep -c '^$1:' /etc/passwd)

if [ $existe -eq 0 ]; then
    echo "The user $1 exists"
    echo ""
else
    echo "The user $1 does not exist"
    echo ""
fi

I've tried the ">/dev/null" solution, the "getent" thing... Agh... No matter what I do, the user always exists, and the code I pasted here is the last one I was trying.

Can you help me? ^^ Thanks in advance.

Sandrituky
  • 131
  • 1
  • 3
  • 12

3 Answers3

5

you need double quotes for variable substituation, and your test condition is wrong:

exists=$(grep -c "^$1:" /etc/passwd)

if [ $exists -eq 0 ]; then
    echo "The user $1 does not exist"
else
    echo "The user $1 exists"
fi

besides, you may use id(1).

georgexsh
  • 15,984
  • 2
  • 37
  • 62
  • Can't we use just `$1` instead of `^$1:`? – User123 Nov 20 '18 at 11:34
  • 1
    @User123 match the username from the start of the line is much safer, and `:` to match the end of the username as passwd file format goes like this. – georgexsh Nov 20 '18 at 11:36
  • Ohh, i thought `$1` could be anything like : username/uid etc., if only username is passed, then it's fine :) – User123 Nov 20 '18 at 11:37
  • 1
    well, that's fair, in that case, one may use `\b$1\b`, to match as a whole, but I dont think that is a good idea, `id` fits better. – georgexsh Nov 20 '18 at 11:38
  • yeah, actually. it could be misleading. – User123 Nov 20 '18 at 11:44
  • Oh, thanks, it worked. It was all about that double quotes. Stupid mistake, but no more stupid than the wrong condition I was making! Thank you a lot! :D – Sandrituky Nov 20 '18 at 12:16
2

You can also just use grep's return value for this:

if grep -q "^$1:" /etc/passwd; then
    printf 'The user %s exists\n' "$1"
else
    printf 'The user %s does not exist\n' "$1"
fi

or, probably better, using getent

if getent passwd "$1" >/dev/null; then
    printf 'The user %s exists\n' "$1"
else
    printf 'The user %s does not exist\n' "$1"
fi

so if you don't actually need the count, you needn't try to save the count and check it later. The exit codes of the commands themselves will tell you if it was found or not.

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
1

You can use grep to act as the conditional

#!/bin/sh
grep -q "^$1:" /etc/passwd && echo exists || echo FALSE

or if you like your imperative conditionals in blocks

#!/bin/sh
if grep -q "^$1:" /etc/passwd ;then
    echo exists
else
    echo FALSE
fi

(Both tested with bash and dash).

Alexx Roche
  • 3,151
  • 1
  • 33
  • 39