Changing a Linux User Name

Here’s how to change a user login name on Linux — the right way.

Keep in mind that you will have to be logged in as root to use these functions and that the old user cannot be logged in or have any other running processes for this to work.

Also note that these will not correct any symbolic links you have pointing the previous home directory.

is-valid-username () { 
  [[ "$1" =~ ^[a-z_][a-z0-9_]{0,31}$ ]] && echo yes && return 0;
  echo no && return 1
}

change-user-name () { 
  local old="$1";
  local new="$2";
  [[ -z "$old" || -z "$new" ]] && echo "usage: change-user-name OLD NEW" && return 1;
  [[ $(is-valid-username "$old") = no ]] && echo "Invalid username: $old" && return 1;
  [[ $(is-valid-username "$new") = no ]] && echo "Invalid username: $new" && return 1;
  groupadd $new;
  usermod -d /home/$new -m -g $new -l $new $old
}