如何从/ etc/passwd中提取最大的UID值?
问题描述:
我想在创建新用户之前预测下一个UID。 由于新的人会把最大的ID值,但并增加了1到它,我想下面的脚本:如何从/ etc/passwd中提取最大的UID值?
biggestID=0
cat /etc/passwd | while read line
do
if test [$(echo $line | cut -d: -f3) > $biggestID]
then
biggestID=$(echo $line | cut -d: -f3)
fi
echo $biggestID
done
let biggestID=$biggestID+1
echo $biggestID
结果我得到1
。这让我感到困惑,我认为问题出在循环上,所以我在fi
的下面添加了echo $biggestID
来检查它的值是否真的在变化,结果发现循环没有问题,因为我得到了许多值高达1000的值。那么为什么biggestID
的值在循环后返回0
?
答
这是因为这行:
cat /etc/passwd | while read line
运行在一个子shell的while
循环,所以biggestID
被在子shell设置,而不是在父shell。
如果您改变环路下面,将工作:
while read line
...
done < /etc/passwd
这是因为while
循环现在在相同的外壳作为主要的脚本来运行,而你只是重定向内容的/etc/passwd
进入循环。
+1
*无用猫被认为有害* :-) – Jens
答
你可以在程序改变的东西是这样的:
newID=$(($(cut -d: -f3 /etc/passwd | sort -n | tail -n 1) +1))
echo $newID
-
cut -d: -f3 /etc/passwd| sort -n | tail -n 1
获取从第三场的passwd -
$(...)
看台上的最大价值,为命令,这里最大的ID的结果 -
newID=$((... + 1))
加1并将结果存储在新ID中
答
你怎么办AWK在一个程序中的所有计算:
awk -F: 'BEGIN {maxuid=0;} {if ($3 > maxuid) maxuid=$3;} END {print maxuid+1;}' /etc/passwd
当你还不想开始使用awk,在你的代码的一些反馈。
biggestID=0
# Do not use cat .. but while .. do .. done < input (do not open subshell)
# Use read -r line (so line is taken literally)
cat /etc/passwd | while read line
do
# Do not calculate the uid twice (in test and assignment) but store in var
# uid=$(cut -d: -f3 <<< "${line}")
# Use space after "[" and before "]"
# test is not needed, if [ .. ] already implicit says so
# (I only use test for onelines like "test -f file || errorfunction")
if test [$(echo $line | cut -d: -f3) > $biggestID]
then
biggestID=$(echo $line | cut -d: -f3)
fi
# Next line only for debugging
echo $biggestID
done
# You can use ((biggestID = biggestID + 1))
# or (when adding one)
# ((++biggestID))
let biggestID=$biggestID+1
# Use double quotes to get the contents literally, and curly brackets
# for a nice style (nothing strang will happen if you add _happy right after the var)
# echo "${biggestID}"
echo $biggestID
的[我如何在bash脚本添加数字(可能的复制http://stackoverflow.com/questions/6348902/how-can-i-add-numbers-in-a-bash-script ) – tddmonkey
可能你有一行像'nobody:x:65534:65533:nobody:/ var/lib/nobody:/ bin/bash',并且想跳过这一行。 –