Linux / Unix Shell Script: Get Current User Name

by on April 9, 2012 · 1 comment· LAST UPDATED April 9, 2013

in , , ,

I am working on a shell script. I need to find out the current user name. How do I find out the current user name under Bash or Ksh shell running on Linux or Unix like operating systems?

You can use the variables $USER, or $USERNAME which are not Bash builtins. These are, however, set as environmental variables in one of the Bash startup files. You can use the id command to get the same information.
Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsBash/ksh
Estimated completion timeN/A

a] $USER - Current user name.

b] $USERNAME - Current user name.

c] id command - Current user name.

Syntax

To get the current user name, type:

 
echo "$USER"
 

Get the current user name and store to a shell variable called $u:

 
u="$USER"
echo "User name $u"
 

Sample outputs:

User name vivek

The syntax for id command is:

 
id -u -n
 

Sample outputs:

vivek

To print numeric UID, run:

 
id -u
 

Sample outputs:

1001

The following script reads user name and store to a variable called _user _uid:

 
#!/bin/bash
_user="$(id -u -n)"
_uid="$(id -u)"
echo "User name : $_user"
echo "User name ID (UID) : $_uid"
 

Shell script example

Make sure only root user can run the following script:

 
#!/bin/bash
 
## get UID 
uid=$(id -u)
 
## Check for it
[ $uid -ne 0 ] && { echo "Only root may enable the nginx-chroot environment to the system."; exit 1; }
 
## Continue main logic with root user
...
..
...
 

A note about $EUID

This variable EUID is readonly. It expands to the effective user ID of the current user, initialized at shell startup. You can use $EUID to find out if user is root or not with the following syntax:

 
# Find out if you are root or not for admin tasks.
(( EUID )) && { echo 'Run this script with root priviliges.'; exit 1; } || echo 'Running as root, starting service...'
 
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 1 comment… read it below or add one }

1 Roman July 14, 2014 at 8:15 am

You forgotten regarding `whoami`

Reply

Leave a Comment

Tagged as: , , , , , , , , , , , ,

Previous Faq:

Next Faq: