I want to predict the next UID before creating a new user. Since the new one will take the biggest ID value yet and adds 1 to it, I thought of the following script:
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
As a result I get 1
. This confused me and I thought that the problem is with the loop, so I added the echo $biggestID
just below fi
to check if its value is truly changing and it turns out there is no problem with the loop as I got many values up to 1000. So why is biggestID
's value returning to 0
after the loop?
It's because of this line:
cat /etc/passwd | while read line
That runs the while
loop in a sub-shell, so biggestID
is being set in the sub-shell, not in the parent shell.
If you change your loop to the following, it will work:
while read line
...
done < /etc/passwd
This is because the while
loop is now running in the same shell as the main script, and you're just redirecting the contents of /etc/passwd
into the loop.