2016-02-28 94 views
2

我想在創建新用戶之前預測下一個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

+0

的[我如何在bash腳本添加數字(可能的複製http://stackoverflow.com/questions/6348902/how-can-i-add-numbers-in-a-bash-script ) – tddmonkey

+0

可能你有一行像'nobody:x:65534:65533:nobody:/ var/lib/nobody:/ bin/bash',並且想跳過這一行。 –

回答

2

這是因爲這行:

cat /etc/passwd | while read line

運行在一個子shell的while循環,所以biggestID被在子shell設置,而不是在父shell。

如果您改變環路下面,將工作:

while read line 
... 
done < /etc/passwd 

這是因爲while循環現在在相同的外殼作爲主要的腳本來運行,而你只是重定向內容的/etc/passwd進入循環。

+1

*無用貓被認爲有害* :-) – Jens

1

你可以在程序改變的東西是這樣的:

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中
1

你怎麼辦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 
相關問題