How to Change User in Linux: The Complete Guide
Linux is a multi-user operating system by design, and managing user identities is one of the most fundamental skills any system administrator needs to master. Whether you're managing a VPS Hosting environment, configuring a web server, or troubleshooting file permission issues after a deployment, understanding how to change users in Linux is essential.
The phrase "change user" in Linux actually covers several distinct operations, each with its own tools, risks, and best practices:
- Switching to another account in the shell (e.g., from
johntoroot) for an interactive session - Running a single command as a different user without fully switching sessions
- Changing which user a service or process runs as — critical for security hardening
- Changing file and directory ownership — essential after migrations, restores, or deployments
- Modifying user account attributes — renaming users, changing UIDs, or adjusting group memberships
This guide covers all of these scenarios in depth, explaining when to use each approach, how to do it safely, and which mistakes to avoid — so you can manage Linux users confidently without breaking permissions, services, or access.
Table of Contents
- Switch to Another User (Interactive Shell)
- Run a Single Command as Another User
- Change the User a Service Runs As (systemd)
- Change File Ownership with chown
- Confirm Your Current Identity
- Modify User Account Attributes
- Quick Reference Cheat Sheet
Switch to Another User (Interactive Shell)
When you need a full interactive terminal session as another user — for system administration, testing application behavior under a different account, or accessing a service account — Linux provides two primary tools: su and sudo.
Using su (Switch User)
The su command substitutes your current user identity with another:
su - usernameThe - flag (also written as -l or --login) is important: it loads the target user's complete login environment, including their home directory, PATH, shell profile, and environment variables. Without the - flag, you inherit much of your current environment, which can cause subtle and confusing behavior — especially when running scripts or services.
To switch directly to root:
su -> Security note: On many modern Linux distributions, the root account password is disabled by default (particularly on Ubuntu-based systems). In these cases, su to root will fail, and sudo is the correct approach.
Using sudo -i (Preferred for Root/Admin Shells)
sudo -iThis gives you a root login shell equivalent to su -, but authenticates using your own sudo privileges rather than requiring the root password. This is the recommended approach on most modern distributions because:
- It avoids the need to share or know the root password
- All actions are logged via the sudo audit trail
- It respects your sudoers configuration and restrictions
Switching to Another User with a Login Shell via sudo
sudo -iu usernameThis combines -i (login shell) and -u (target user), giving you a clean login environment as the specified user — without needing that user's password.
Run a Single Command as Another User
Often you don't need a full interactive session — you just need to execute one command with a different identity. This is the most common and safest pattern for privilege escalation.
Using sudo -u
sudo -u username whoamisudo -u postgres psqlThe second example is extremely common in database administration — switching to the postgres system user to access PostgreSQL without password authentication.
Run a Command with a Clean Login Environment
sudo -iu username command_hereThis ensures the command runs with the target user's full environment, not your current session's variables.
Run a Command as Root
sudo systemctl restart nginxThis is the standard pattern for administrative tasks: run a single privileged command without opening a root shell.
Change the User a Service Runs As (systemd)
On virtually all modern Linux distributions, systemd manages services. For security, every service should run under a dedicated, unprivileged user account rather than root. Running services as root is a significant security risk — if the service is compromised, the attacker gains root access to the entire system.
This is especially important on Dedicated Servers and production VPS environments where multiple services may be running simultaneously.
Check the Current Service Configuration
systemctl cat myservice.serviceLook for the User= and Group= directives in the [Service] section:
[Service]
User=www-data
Group=www-dataOverride the Service User (Safe Method)
Rather than editing the original unit file (which may be overwritten on package upgrades), use systemctl edit to create a drop-in override:
sudo systemctl edit myservice.serviceThis opens an editor where you add:
[Service]
User=myuser
Group=mygroupSave the file, then apply the changes:
sudo systemctl daemon-reload
sudo systemctl restart myservice.serviceVerify the Service Is Running as the Correct User
systemctl status myservice.serviceps -eo user,pid,cmd | grep myserviceInspect Any Running Process's User
ps -eo user,pid,cmd | grep nginxps -p <PID> -o user,group,cmd> Important: Linux does not allow you to change the user of an already-running process in place. You must restart the process (or configure the service manager to launch it under the correct user) for the change to take effect.
Change File Ownership with chown
File ownership is a core part of Linux's permission model. After migrations, deployments, backups, or restores, ownership can end up assigned to the wrong user — causing permission denied errors, broken web applications, or inaccessible data. The chown command is your primary tool for correcting this.
This is a common task when setting up Shared Web Hosting environments or deploying web applications on a VPS.
Change the Owner of a File
sudo chown username file.txtChange Both Owner and Group
sudo chown username:groupname file.txtRecursive Ownership Change (Use with Caution)
sudo chown -R username:groupname /var/www/siteThe -R flag applies the change recursively to all files and subdirectories. Use this carefully — applying it to the wrong path (e.g., / or /etc) can break your entire system.
Preserve Symlinks
sudo chown -h username:groupname symlinkWithout -h, chown follows symbolic links and changes the ownership of the target file, not the symlink itself. Use -h when you specifically want to change symlink ownership.
Preview Ownership Before Making Changes
For large directory trees, always preview before applying a recursive chown:
find /path -maxdepth 2 -printf '%u:%g %pn' | headThis shows the current owner and group for the top two levels of the directory tree, letting you confirm the scope of the change before committing.
Confirm Your Current Identity
Before making changes, always verify who you are and what context you're operating in. This prevents accidental changes made under the wrong account.
Check Your Current User
whoamiGet Full Identity Information (User, Groups, UIDs)
idExample output:
uid=1000(alice) gid=1000(alice) groups=1000(alice),27(sudo),1001(docker)See Who Is Logged In to the System
whowCheck the Original User When Using sudo
When you escalate with sudo, two environment variables are relevant:
echo $USER # The current effective user (root)
echo $SUDO_USER # The original user who invoked sudo (e.g., alice)This distinction matters in scripts — $SUDO_USER tells you who actually ran the command.
Modify User Account Attributes
Sometimes "changing user" means modifying the account itself: renaming it, changing its UID, or adjusting group memberships. These are permanent, system-wide changes that can affect logins, file permissions, and service access.
> Best practice: Before making account modifications, ensure the user is logged out and no processes are running under that account.
Rename a User (Change Username)
sudo usermod -l newname oldnameThis changes the login name but does not automatically rename the home directory. To also move and rename the home directory:
sudo usermod -d /home/newname -m newnameIf the user has a primary group with the same name as their old username (which is the default on most distributions), update the group name too:
sudo groupmod -n newname oldnameChange a User's UID
sudo usermod -u 2001 username> Critical: After changing a UID, all files previously owned by the old UID will appear as owned by an unknown numeric ID. You must fix this immediately:
sudo find / -user oldUID -exec chown -h username {} ;Replace oldUID with the previous numeric UID. This command searches the entire filesystem for files with the old UID and reassigns them to the new username.
Add a User to a Group
The most common use case is granting sudo access to a user:
Debian/Ubuntu:
sudo usermod -aG sudo usernameRHEL / AlmaLinux / Rocky Linux:
sudo usermod -aG wheel usernameThe -a flag is critical — it appends the user to the group without removing them from existing groups. Omitting -a will replace all group memberships with only the specified group.
Verify Group Membership
id usernameQuick Reference Cheat Sheet
Here's a consolidated reference for all the user-switching and management operations covered in this guide:
| Task | Command | |
|---|---|---|
| Switch to another user (login shell) | su - username | |
| Switch to another user via sudo | sudo -iu username | |
| Open a root shell | sudo -i | |
| Run a command as another user | sudo -u username command | |
| Run a command as postgres | sudo -u postgres psql | |
| Check current user | whoami | |
| Check full identity and groups | id | |
| Check original sudo invoker | echo $SUDO_USER | |
| Change file owner | sudo chown username file | |
| Change file owner and group | sudo chown username:group file | |
| Recursive ownership change | sudo chown -R username:group /path | |
| Preview directory ownership | find /path -maxdepth 2 -printf '%u:%g %pn' | |
| Change service user (systemd) | sudo systemctl edit myservice.service | |
| Reload systemd after changes | sudo systemctl daemon-reload | |
| Verify process user | `ps -eo user,pid,cmd | grep service` |
| Rename a user | sudo usermod -l newname oldname | |
| Move home directory | sudo usermod -d /home/newname -m newname | |
| Change UID | sudo usermod -u 2001 username | |
| Fix ownership after UID change | sudo find / -user oldUID -exec chown -h username {} ; | |
| Add user to sudo group | sudo usermod -aG sudo username | |
| Verify group membership | id username |
Summary
Managing users in Linux is not a single operation — it's a family of related tasks, each with its own tools and implications:
- Use
sudo -iu usernamefor interactive sessions as another user (preferred oversuon modern systems) - Use
sudo -u username commandfor running individual commands with a different identity - Use
systemctl editto safely change which user a systemd service runs as - Use
chownto fix file ownership after deployments, migrations, or permission issues - Use
usermodfor permanent account changes — renaming, UID changes, and group management
Understanding these distinctions helps you avoid common mistakes like breaking service permissions, locking yourself out of files, or accidentally granting excessive privileges.
If you're running Linux-based infrastructure — whether it's a web server, a database, or a custom application stack — having a properly configured hosting environment makes user management significantly easier. AlexHost offers flexible VPS Control Panels and VPS with cPanel options that give you full root access alongside intuitive management interfaces, so you can apply everything in this guide with confidence.
