logo

Shell - Users and Groups

Users and Groups Shell Commands

check current user uid/gid:

# List IDs, e.g. as root
$ id
uid=0(root) gid=0(root) groups=0(root)

# List IDs of a user, e.g. ubuntu (one uid, one gid, a list of groups)
$ id ubuntu
uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),4(adm),20(dialout),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),109(netdev),110(lxd),999(docker)

# Get uid only
$ id -u
1000

# Get gid only
$ id -g
1000

# List groups of the user
$ groups ubuntu
ubuntu : ubuntu adm dialout cdrom floppy sudo audio dip video plugdev netdev lxd docker

# List all groups
$ cat /etc/group

# List all users
$ cat /etc/passwd

# Get the read-only, effective user ID
$ echo $EUID
1000

# Get the current user name
$ whoami
ubuntu

# Or check `$USER`
$ echo $USER
ubuntu

getent

Find out the members of a group with the name developers you would use the following command:

$ getent group developers

Manage Users and Groups

groupadd: add a new group

$ sudo groupadd docker

usermod: modify user, e.g. add user to group docker

$ sudo usermod -aG docker $USER

root

How to change to root user?

# runs the specified command (su) as root
$ sudo su

# maybe a cleaner (in my opinion) way of running `sudo su`.
$ sudo -i

# runs the su command as the user who invoked it
$ su - root

Why I cannot login or ssh as root?

It works to login or ssh with a user name then sudo su but does not work to directly login or ssh as root?

Password for root is not set in Ubuntu which means the root login is disabled by default.

To set the password for root:

$ sudo passwd root

Why some commands are only available with sudo?

The shell will lookup commands in PATH.

$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

It is possible that the root user has a different PATH from a normal user (check your config files like /etc/profile, ~/.bashrc etc). E.g. root user may have /usr/local/sbin or /usr/sbin or /sbin while normal user only has the normal bin folders in the PATH.

The other case may also happen: you installed some program in PATH as a normal user, but needs root permission to execute, for example, if you install node in your own folder while you need $ sudo node bin/www to serve it, you will get an error saying node cannot be found.

Solution:

$ sudo env PATH=$PATH [COMMAND]

this will use your own PATH when executing the COMMAND, e.g.

$ sudo env PATH=$PATH node bin/www

or add this to ~/.bashrc

alias sudo='sudo env PATH=$PATH'