Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to check if an user exists? [duplicate]

Tags:

bash

shell

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.

like image 987
Sandrituky Avatar asked Sep 08 '25 03:09

Sandrituky


1 Answers

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).

like image 132
georgexsh Avatar answered Sep 10 '25 01:09

georgexsh