我正在编写一个脚本,用于在命令行上将新用户添加到OS X系统。我知道我可以使用以下命令列出系统中所有用户ID的用户:
dscl . -list /Users UniqueID
给出了类似的东西:
xxxxxxx 937
xxxxxxxx 939
xxxxx 940
xxxxxx 941
如何从此输出中检索最大的用户ID以存储在变量中?
答案 0 :(得分:10)
这将为您提供ID最高的行:
dscl . -list /Users UniqueID | sort -nr -k 2 | head -1
答案 1 :(得分:2)
只需awk
awk '$2>m{m=$2}END{print m}' file
将其存储在变量do:
中highestID=$(awk '$2>m{m=$2}END{print m}' file)
答案 2 :(得分:1)
Scott Hunter和SiegeX的回答+一些Python的组合:
# Max User ID
MAXUID=`dscl . list /Users UniqueID | awk '$2>m{m=$2}END{print m}'`
# Next User ID
NEXTUID=$(( $MAXUID + 1 ))
# Three Ways to Retrieve Specific User ID
UID=`id -u $USER`
UID=`dscl . list /Users/$USER | awk '{print $2}'`
UID=`python -c 'import pwd,os; print pwd.getpwnam(os.getenv("USER")).pw_uid'`
# Three Ways to Retrieve Max Group ID
MAXGID=`dscacheutil -q group | grep gid | awk '$2>n{n=$2}END{print n}'`
MAXGID=`dscl . list /Groups PrimaryGroupID | awk '$2>n{n=$2}END{print n}'`
MAXGID=`python -c 'import grp;print grp.getgrgid(max(g.gr_gid for g in grp.getgrall()))'`
# notice the python method has a different max groupid
# this is because nobody/nouser groups have negative values for PrimaryGroupID in dscl
# but python gives these absolute values:
# 2^32 = 4294967296
# if you subtract one you get 4294967295 (the max group id python returns)
# Two Ways to Retrieve Specific Group ID (i.e. staff)
STAFFGID=`dscl . read /Groups/staff PrimaryGroupID | awk '{print $2}'`
STAFFGID=`python -c 'import grp; print grp.getgrnam("staff").gr_gid'`