Skip to content

Instantly share code, notes, and snippets.

@LukeCarrier
Last active September 27, 2019 11:28
Show Gist options
  • Save LukeCarrier/1b0531d387e96b597866eba0d04116b2 to your computer and use it in GitHub Desktop.
Save LukeCarrier/1b0531d387e96b597866eba0d04116b2 to your computer and use it in GitHub Desktop.
uid/gid tool
#!/bin/bash
# Change user uids and group gids, preserving file permissions on all mounted
# volumes.
change_user_uid() {
if (( $# != 2 )); then
echo "${0}: usage: ${0} USERNAME NEW_UID" >&2
return 1
fi
local username="$1"
local new_uid="$2"
if ! [[ "$new_uid" =~ ^[0-9]+$ ]]; then
echo "${0}: new_uid must be numeric" >&2
return 1
fi
if [[ "$(getent passwd "$new_uid" | cut -d: -f1)" == "$username" ]]; then
echo "${0}: user's uid already matches" >&2
elif getent passwd "$new_uid" >/dev/null; then
echo "${0}: new_uid ${new_uid} already taken; choose another" >&2
return 1
fi
if (( $(ps --no-headers -u "$username" | wc -l) > 0 )); then
echo "${0}: user ${username} has processes open; stop them first" >&2
return 1
fi
chown --changes --from "$username" --recursive "$new_uid" / || true
usermod --uid "$new_uid" "$username"
}
change_group_gid() {
if (( $# != 2 )); then
echo "${0}: usage: ${0} GROUP_NAME NEW_GID" >&2
return 1
fi
local group_name="$1"
local new_gid="$2"
if ! [[ "$new_gid" =~ ^[0-9]+$ ]]; then
echo "${0}: new_gid must be numeric" >&2
return 1
fi
if getent group "$new_gid" >/dev/null; then
echo "${0}: new_gid ${new_gid} already taken; choose another" >&2
return 1
fi
find / -group "$group_name" -exec chgrp --changes --recursive "$new_gid" {} \; || true
groupmod --gid "$new_gid" "$group_name"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment