要獲得用戶的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
我想你會想用'useradd'或'adduser'。 'getent'和'id'也派上用場。 – 2010-09-06 08:42:07