How to get unique `uid`?
Solution 1
To get a user's UID:
cat /etc/passwd | grep "^$usernamevariable:" | cut -d":" -f3
To add a new user to the system the best option is to use useradd
, or adduser
if you need a fine-grained control.
If you really need just to find the smallest free UID, here's a script that finds the smallest free UID value greater than 999 (UIDs 1-999 are usually reserved to system users):
#!/bin/bash
# return 1 if the Uid is already used, else 0
function usedUid()
{
if [ -z "$1" ]
then
return
fi
for i in ${lines[@]} ; do
if [ $i == $1 ]
then
return 1
fi
done
return 0
}
i=0
# load all the UIDs from /etc/passwd
lines=( $( cat /etc/passwd | cut -d: -f3 | sort -n ) )
testuid=999
x=1
# search for a free uid greater than 999 (default behaviour of adduser)
while [ $x -eq 1 ] ; do
testuid=$(( $testuid + 1))
usedUid $testuid
x=$?
done
# print the just found free uid
echo $testuid
Solution 2
Instead of reading /etc/passwd
, you can also do it in a more nsswitch-friendly way:
getent passwd
Also don't forget that there isn't any guarantee that this sequence of UIDs will be already sorted.
Solution 3
To get UID given an user name "myuser":
cat /etc/passwd | grep myuser | cut -d":" -f3
To get the greatest UID in passwd file:
cat /etc/passwd | cut -d":" -f3 | sort -n | tail -1
Solution 4
I changed cat /etc/passwd
to getent passwd for Giuseppe's answer.
#!/bin/bash
# From Stack Over Flow
# http://stackoverflow.com/questions/3649760/how-to-get-unique-uid
# return 1 if the Uid is already used, else 0
function usedUid()
{
if [ -z "$1" ]
then
return
fi
for i in ${lines[@]} ; do
if [ $i == $1 ]
then
return 1
fi
done
return 0
}
i=0
# load all the UIDs from /etc/passwd
lines=( $( getent passwd | cut -d: -f3 | sort -n ) )
testuid=999
x=1
# search for a free uid greater than 999 (default behaviour of adduser)
while [ $x -eq 1 ] ; do
testuid=$(( $testuid + 1))
usedUid $testuid
x=$?
done
# print the just found free uid
echo $testuid
Pablo
Updated on June 27, 2022Comments
-
Pablo almost 2 years
I'm making a bash script which should create an ftp user.
ftpasswd --passwd --file=/usr/local/etc/ftpd/passwd --name=$USER --uid=[xxx] --home=/media/part1/ftp/users/$USER --shell=/bin/false
The only supplied argument to script is user name. But
ftpasswd
also requiresuid
. How do I get this number? Is there an easy way to scanpasswd
file and get the max number, increment it and use it? Maybe it's possible to obtain that number from the system?