Help with the original shellscript
The test in the if statement is causing the problem. I suggest the following shellscript,
#!/bin/bash
read -p "donner l UID " cheruid
if [ "$(grep -w "^$cheruid" /etc/passwd)" != "" ]
then
grep -w "$cheruid" /etc/passwd | cut -d ":" -f "1" | xargs echo "user is : "
else
echo "user not found"
fi
Edit1: I added a ^
in the test to only look for matches at the beginning of the line.
Edit2: since :
is a separator, you can remove it and everything after, and use the result directly in the echo
line, if accepted in the test, and simplify the shellscript to
#!/bin/bash
read -p "donner l UID " cheruid
cheruid=${cheruid%%:*}
user=$(grep -wo "^$cheruid" /etc/passwd)
if [ "$user" != "" ]
then
echo "user is : $user"
else
echo "user not found"
fi
This helps you make a good bash shellscript.
Efficient and more general method to find user IDs with id
If you want an efficient way to check if a particular user name exists, <test-name>
, you can use id
, as indicated in another answer to your question by Stéphane Chazelas:
id -un -- <test-name>
for example
id -un -- mehdi
id
will find not only user IDs stored in /etc/passwd
but also those managed and stored in other ways, for example LDAP, which is common in professional server systems as commented by Matteo Italia.
If you want to scan all users
system users, in many linux systems with user numbers < 1000
'human' users, in many linux systems with user numbers >= 1000
and assuming that all users have number < 2000 (modify if you need)
you can use the following bash
one-liner, which uses a loop with id
,
for ((i=0;i<2000;i++));do name=$(id -un $i 2>/dev/null);if [ $? -eq 0 ];then echo "$i: $name" ;fi;done
If you want to see only the 'human' users and assume that no user ID number is skipped (no deleted user), the following bash
oneliner is very fast,
i=1000;while true;do name=$(id -un $i 2>/dev/null);if [ $? -eq 0 ];then echo "$name" ;else break;fi;i=$((i+1));done
but it is more reliable to assume that some ID numbers may be skipped (deleted users),
for ((i=1000;i<2000;i++));do name=$(id -un $i 2>/dev/null);if [ $? -eq 0 ];then echo "$i: $name" ;fi;done
There are also users
and who
which print the user names of users currently logged in to the current host.