如何获得唯一的`uid`?
我正在创建一个应该创建一个ftp用户的bash脚本。如何获得唯一的`uid`?
ftpasswd --passwd --file=/usr/local/etc/ftpd/passwd --name=$USER --uid=[xxx]
--home=/media/part1/ftp/users/$USER --shell=/bin/false
唯一提供给脚本的参数是用户名。但ftpasswd
也需要uid
。我如何得到这个号码?有没有简单的方法来扫描passwd
文件并获得最大数量,增加它并使用它?也许有可能从系统中获得这个数字?
要获得用户的UID:
cat /etc/passwd | grep "^$usernamevariable:" | cut -d":" -f3
要将新用户添加到系统中,最好的选择是使用useradd
或adduser
,如果您需要af无粒度控制。
如果你真的只需要找到最小的自由UID,下面是找到的最小的自由UID值大于999的信息(UID 1-999通常保留给系统用户)的脚本:
#!/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
总是通过“cmd 2015-04-23 07:48:45
@RaúlSalinas-Monteagudo你会介意粘贴更好的命令吗? – ffghfgh 2017-08-08 10:08:31
要获得UID给出一个用户名 “为myuser”:
cat /etc/passwd | grep myuser | cut -d":" -f3
要获得passwd文件的最大UID:
cat /etc/passwd | cut -d":" -f3 | sort -n | tail -1
我喜欢最后一种方法;然而,很多时候'/ etc/passwd'会有一个UID 65534('nfsnobody')的入口。这需要绕过如下:'grep -v':65534:'/ etc/passwd | cut -d:-f3 | sort -n | tail -1' – sxc731 2017-02-07 15:18:50
相反阅读/etc/passwd
,你也可以做一个更nsswitch的友好的方式:
getent passwd
另外不要忘记,没有任何保证的UID的这个序列将已经排序。
我将猫猫/etc/passwd
更改为getent passwd给Giuseppe的回答。
#!/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
这是一个非常短的方法:
#!/bin/bash
uids=$(cat /etc/passwd | cut -d: -f3 | sort -n)
uid=999
while true; do
if ! echo $uids | grep -F -q -w "$uid"; then
break;
fi
uid=$(($uid + 1))
done
echo $uid
我想你会想用'useradd'或'adduser'。 'getent'和'id'也派上用场。 – 2010-09-06 08:42:07