【linux】 ユーザーをグループに追加する際は gpasswd -a か usermod -aG を使う方がいい
ユーザーをあるグループに追加する場合はusermod -aG
コマンドかgpasswd -a
を利用した方がいいという話です。
ユーザーをグループに追加する手段
ユーザーを作成する場合に、そのユーザーをグループに所属させる方法として主に以下の手段が考えられる
- user作成時にオプションで所属させるグループを指定する
# useradd -g [主グループ名 or gid] -G [サブグループ名 or gid] [ユーザー名]
usermod
コマンドで所属グループ指定
# usermod -g [主グループ名 or gid] -G [サブグループ名 or gid] [ユーザー名]
usermod
コマンドに -aG オプションを付けて追加グループ指定
# usermod -aG [グループ名] [ユーザー名]
gpasswd
コマンドで特定のグループに指定ユーザーを追加する
# gpasswd -a [ユーザー名] [グループ名]
usermodを使用する場合の注意点
usermod
コマンドを使用する際、-a
オプションをつけない状態で-G
オプションで所属グループを指定した場合、指定したグループにのみ所属する状態に変更されます。そのため、指定によっては元々所属していたグループから外れる恐れがありますので注意が必要です。
マニュアル
# man usermod -a, --append Add the user to the supplementary group(s). Use only with the -G option. -G, --groups GROUP1[,GROUP2,...[,GROUPN]]] A list of supplementary groups which the user is also a member of. Each group is separated from the next by a comma, with no intervening whitespace. The groups are subject to the same restrictions as the group given with the -g option. If the user is currently a member of a group which is not listed, the user will be removed from the group. This behaviour can be changed via the -a option, which appends the user to the current supplementary group list.
実行ログ
わかり辛いかもですが、redmine というユーザーに対して gpasswd -a
、usermod -G
、usermod -aG
でグループ追加操作を行った操作ログです。
[root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# id redmine uid=502(redmine) gid=502(redmine) groups=502(redmine) [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# gpasswd -a redmine wheel Adding user redmine to group wheel [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# id redmine uid=502(redmine) gid=502(redmine) groups=502(redmine),10(wheel) [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# usermod -G redmine redmine [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# id redmine [uid=502(redmine) gid=502(redmine) groups=502(redmine) [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# usermod -aG wheel redmine [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# [root@vagrant-centos65 ~]# id redmine uid=502(redmine) gid=502(redmine) groups=502(redmine),10(wheel)