UESPWiki:Scripts/change user ids

The UESPWiki – Your source for The Elder Scrolls since 1995
Jump to: navigation, search
#!/bin/sh
#
# $1 = user name
# $2 = new user id
# $3 = new group id
#

if [ -z $1 ] || [ -z $2 ] || [ -z $3 ]
then
        echo "     Error: Three parameters required (username, new userid, new groupid)!"
        exit 1
fi

USERNAME=$1
NEWUSERID=$2
NEWGROUPID=$3

OLDUSERID=`id -u $USERNAME`

if [ $? != 0 ] || [ -z $OLDUSERID ]
then
        echo "     Error: Unknown user '$USERNAME'!"
        exit 1
fi

OLDGROUPID=`id -g $USERNAME`

if [ $? != 0 ] || [ -z $OLDGROUPID ]
then
        echo "     Error: Unknown group for user '$USERNAME'!"
        exit 1
fi

RESULT=`echo $NEWUSERID | egrep "^[0123456789]+$"`

if [ $? != 0 ] || [ $NEWUSERID -lt 0 ]
then
        echo "     Error: New user id '$NEWUSERID' must be an integral number!"
        exit 1
fi

RESULT=`echo $NEWGROUPID | egrep "^[0123456789]+$"`

if [ $? != 0 ] || [ $NEWGROUPID -lt 0 ]
then
        echo "     Error: New group id '$NEWGROUPID' must be an integral number!"
        exit 1
fi

if [ $NEWUSERID != $OLDUSERID ]
then
        RESULT=`egrep ".*:.*:$NEWUSERID:" /etc/passwd`

        if [ $? == 0 ]
        then
                echo "     Error: New user id '$NEWUSERID' is already in use: $RESULT"
                exit 1
        fi
fi

 if [ $NEWGROUPID != $OLDGROUPID ]
 then
         RESULT=`egrep ".*:.*:.*:$NEWGROUPID:" /etc/passwd`
 
         if [ $? == 0 ]
         then
                 echo "     Error: New group id '$NEWGROUPID' is already in use: $RESULT"
                 exit 1
         fi
fi

if [ $NEWUSERID != $OLDUSERID ]
then
        echo "     Changing user '$USERNAME' ID from $OLDUSERID to $NEWUSERID."

        usermod -u $NEWUSERID $USERNAME
        find / -user $OLDUSERID -exec chown $NEWUSERID {} \;
fi

if [ $NEWGROUPID != $OLDGROUPID ]
then
        echo "     Changing user '$USERNAME' group ID from $OLDGROUPID to $NEWGROUPID."

        groupmod -g $NEWGROUPID $USERNAME
        usermod -g $NEWGROUPID $USERNAME
        find / -group $OLDGROUPID -exec chown :$NEWGROUPID {} \;
fi