tags:

views:

69

answers:

2

I'm making a bash script which should create an ftp user.

ftpasswd --passwd --file=/usr/local/etc/ftpd/passwd --name=$USER --uid=[xxx]
     --home=/media/part1/ftp/users/$USER --shell=/bin/false

The only supplied argument to script is user name. But ftpasswd also requires uid. How do I get this number? Is there an easy way to scan passwd file and get the max number, increment it and use it? Maybe it's possible to obtain that number from the system?

+1  A: 

To get UID given an user name "myuser":

 cat /etc/passwd | grep myuser | cut -d":" -f3

To get the greatest UID in passwd file:

 cat /etc/passwd | cut -d":" -f3 | sort -n | tail -1
Fernando Miguélez
+1  A: 

To get a user's UID:

cat /etc/passwd | grep "^$usernamevariable:" | cut -d":" -f3

To add a new user to the system the best option is to use useradd, or adduser if you need a fine-grained control.

If you really need just to find the smallest free UID, here's a script that finds the smallest free UID value greater than 999 (UIDs 1-999 are usually reserved to system users):

#!/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
Giuseppe Cardone