Current user in linux command

Get the Current User in Linux

Finally, let’s summarize what we’ve learned in a table (assuming the login user is kent ): Approaches After login After su After su guest With sudo $USER kent kent guest root whoami kent root root root id -nu kent root root root logname kent kent kent kent For the sysadmins, it is routine to monitor user details like who are active and who are not, who logged in in last 2 days, which users belong to a given group etc etc. To help these requirements, Linux provides below list of commands which can be used to gather various types of information about the users.

Get the Current User in Linux

1. Overview

When we work on the Linux command line, sometimes, we want to know who the current user is. Moreover, when we write a shell script, we may want to know who is running the script.

In this tutorial, let’s figure out how to identify the current user in Linux.

2. Introduction to the Problem

Various commands can get the current user in Linux. We’ll explore some of them in this tutorial. Also, for each method, we’ll discuss what they’ll report if we change to another user using the su command.

Further, we shouldn’t forget that the sudo command may hide the real user, too. Therefore, we’ll address what various approaches will print if they’re called by sudo .

Next, let’s see them in action.

3. Reading the $USER Variable

After we’ve logged into a Linux system through a login shell, the system sets the $USER environment variable by the current login user. Therefore, we can read the $USER variable to get the current user’s name:

3.1. After Executing the su Command

Since the su command does not invoke a login shell by default, if we switch to root using the su command, the $USER variable still stores the original login user :

kent$ echo $USER kent kent$ su Password: root# echo $USER kent

However, if we execute su USERNAME , the login shell will be invoked. Thus, the $USER variable will hold the USERNAME we’ve switched to:

kent$ su guest Password: guest$ echo $USER guest
3.2. With the sudo Command

We run the command with superuser privileges when we execute a command with sudo . So, for example, we log in as the user kent , and when we execute sudo some-command , the login user is still kent , but the effective user is root .

Next, let’s see which user $USER will store in case of sudo . But, first, let’s create a pretty simple script:

$ cat user-by-var.sh #!/bin/bash echo "The current user by reading \$USER: $USER"

Now, let’s execute the script with sudo :

$ sudo ./user-by-var.sh [sudo] password for kent: The current user by reading $USER: root

As the output above shows, if our script gets executed with sudo , the $USER variable holds the effective user root .

3.3. The $USER Variable Can Be Overwritten

Finally, we should keep in mind that $USER is an environment variable. That is to say, we can overwrite it at any time . Therefore, if we want to get the current user in our shell script, $USER is not reliable.

Читайте также:  Mint linux live iso

Next, let’s execute our small script twice, with and without changing the $USER variable:

kent$ ./user-by-var.sh The current user by reading $USER: kent kent$ USER=superman; ./user-by-var.sh The current user by reading $USER: superman 

As the example above shows, if our script reads $USER to get the current user, the user can easily cheat the script by changing the $USER variable.

4. Using the whoami Command

The whoami command prints the effective username of the current user when invoked :

4.1. After Executing the su Command

After we switch to root by calling su , the effective user becomes root . Therefore, unlike the $USER variable, whoami will print root :

kent$ su Password: root# whoami root

If we execute su with a username, whoami will print the username as well:

kent$ su guest Password: guest$ whoami guest
4.2. With the sudo Command

Similar to the $USER variable, the whoami command reports the effective user root if we execute it with sudo :

kent$ sudo whoami [sudo] password for kent: root

5. Using the id Command

Additionally, the id command can print the real and effective user and group id :

kent$ id uid=1000(kent) gid=1000(kent) groups=1000(kent),7(lp),10(wheel), . 108(vboxusers),990(docker)

Of course, if we’re only interested in the username, we can pass the -nu options to the id command :

5.1. After Executing the su Command

Same as the whoami command, after we switch to another using su , the id command will print the new user’s name :

kent$ su Password: root# id -nu root kent$ su guest Password: guest$ whoami guest 
5.2. With the sudo Command

As the id command reports the real and the effective user, it’ll print root if we run it with the sudo command :

kent$ sudo id -nu [sudo] password for kent: root 

6. Using the logname Command

logname is a member of the coreutils package. As the name implies, the logname command prints the user’s login name :

6.1. After Executing the su Command

As the logname command prints the user’s login name, after we “ su ” to another user, the logname command still reports the original login user no matter whether we pass a username to the su command:

kent$ su Password: root# logname kent kent$ su guest Password: kent$ logname kent 
6.2. With the sudo Command

Unlike the whoami and id commands, when we call logname with sudo , it still prints the original login name :

kent$ sudo logname [sudo] password for kent: kent

7. Conclusion

In this article, we’ve explored several approaches to identify the current user in the Linux command line. Further, we’ve discussed their behaviors if we execute them with the su and sudo commands.

Finally, let’s summarize what we’ve learned in a table (assuming the login user is kent ):

Approaches After login After su After su guest With sudo
$USER kent kent guest root
whoami kent root root root
id -nu kent root root root
logname kent kent kent kent

How to List Users in Linux, The /etc/passwd file is a plain-text-based database that contains info about all the users in the system. The file is owned by root with the file permission 644

Читайте также:  Adding samba users in linux

How to Find User Account Info and Login Details in Linux?

For the sysadmins, it is routine to monitor user details like who are active and who are not, who logged in in last 2 days, which users belong to a given group etc etc. To help these requirements, Linux provides below list of commands which can be used to gather various types of information about the users.

id Command

It gives the id details of users including the group id along with the secondary group IDs and names of a user choosen by the system. But you also ask for a specific user’sdeatils by giving the userid value in the command.

ubuntu@ubuntu:~$ id ubuntu@ubuntu:~$ id 2112

Running the above code gives us the following result:

uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare) uid=2112(uname1) gid=3421(uname1) groups=3421(uname1)

groups

It displays the group names the currently logged in user belongs to.

Running the above code gives us the following result −

ubuntu adm cdrom sudo dip plugdev lpadmin sambashare

getnet

This command looks into passed file and gets the user details form there.

ubuntu@ubuntu:~$ getent passwd

Running the above code gives us the following result −

root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin …… ………

lslogins

The lslogins command displays details of the known users of the system.

Running the above code gives us the following result −

UID USER PROC PWD-LOCK PWD-DENY LAST-LOGIN GECOS 0 root 135 root 1000 ubuntu 70 23:04:25 ubuntu16LTS. 2112 uname1 0 storefront 9002 uname4 0 HR

w

It displays the current users logged in to the system and the processes they are running.

Running the above code gives us the following result −

08:13:17 up 12:26, 1 user, load average: 0.00, 0.00, 0.00 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT ubuntu tty7 :0 23:04 12:58m 1:23 0.34s /sbin/upstart –user

How to Determine the Current User Account in Linux, To quickly reveal the name of the logged in user from the GNOME desktop used on Ubuntu and many other Linux distributions, click the system menu

Finding out the default shell of a user within a shell script

I was wondering if there’s a way to find out the default shell of the current user within a shell script?

Use case: I am working on a script that sets an alias for a command and this alias is set within a shell script.

!# /bin/bash alias = 'some command to set the alias' 

There’s a logic in the script where it tries to find the default shell of the user that executes the script and adds this alias in the respective ~/.bashrc or ~/.zshrc file

But as I am adding a shebang in the front of the script and explicitly asking it to use bash, answers posted here always return bash as expected although I am executing this script on a ZSH terminal.

Is there a way to get the shell type where the script is executed regardless of the shebang set?

I am looking for a solution that works on both Mac and all the linux based bistro.

The environment variable, SHELL would always expands to the default login shell of the invoking user (gets the value from /etc/passwd ).

For any other given user, you need to do some processing with /etc/passwd , here is a simple awk snippet:

awk -F: -v user="foobar" '$1 == user ' /etc/passwd 

Replace foobar with the actual username.

Читайте также:  Связь между компьютерами linux

If you have ldap (or something similar in place), use getent to get the database instead of directly parsing /etc/passwd :

getent passwd | awk -F: -v user="foobar" '$1 == user ' 

or cleanest approach, let getent do the parsing (thanks to @Kusalananda):

getent passwd foobar | awk -F: '' 
$ finger $USER|grep -oP 'Shell: \K.*' /bin/mksh 

Since getent isn’t a standard command on MacOS, you may wish to use a lower level getpwuid call that will consult the naming services the machine is configured for. This may require calling out to perl or python , which are pretty common across most Unix-like platforms

eg this will return the shell for the current user:

grep ^$USER: /etc/passwd | cut -f 7 -d : 

How Do I Change My Username in Linux?, Step 1- User Description: To change the current username in Linux, we use the command to know about the current user and directory. “Whoami” is used to display

Retrieving infor for certain users in linux

I have this code to generate user account info. the problem is I have a line for user name where you will type a user name and only retrieve the information for that specified user name. but the code retrieves information for all users on the system.

#! /bin/bash #This script returns import information about the user name on the system echo "PLease enter name to continue:" read SuppliedName for user in $(cut -d: -f1 /etc/passwd) #while [ "$SuppliedName" == "$USER" ] do IFS=$'\n' userinfo=$(grep $user: /etc/passwd) comment=$(echo $userinfo | cut -d: -f5) home=$(echo $userinfo | cut -d: -f6) groups=$(groups $user | cut -d: -f2) #Skip users that do not have '/home' in the path to their home directory if [ $(echo "$home" | grep -v '/home/') ] then continue fi echo "Username: $user" echo "User Info: $comment" echo "Home Directory: $home" echo "Groups: $groups" echo "Disk usage: $(du -sh $home)" last=$(last $user | head -1) if [ $( echo $last | wc -c ) -gt 1 ] then echo "Last login: " echo "$last" else echo "User has never logged in!" fi echo "" echo "--" echo "" done 
  1. You’re missing comparison between $user and $suppliedName , and since you are iterating over /etc/passwd to get all user data, you print it.
  2. grep $user: /etc/passwd will grep all lines which contains ‘$user:’ including those users who has GECOS starting with that name (correct regex is ^$user: )
  3. This code only checks local users, so no LDAP. The cleaner way is to use getent .

All in all, i would be using finger for this. Or rewritten main loop as:

getent passwd $suppliedName | ( IFS=: while read UNAME SHADOW UID_ GID GECOS HOME SHELL ; do # Your code goes here done ) 

You can do this another way with a lot less effort and handle the non-match a bit more gracefully, e.g.

#!/bin/bash printf "PLease enter name to continue: " ## use printf read -r name info="$(grep "^$name" /etc/passwd)" ## read line into info if [ -n "$info" ]; then ## test that info is not empty, then call awk awk -F : '' \  

Example Use/Output

$ bash getuser.sh PLease enter name to continue: david Username: david User Info: David C. Rankin Home Directory: /home/david Groups: david : david adm lp sys uucp wheel vboxusers 

Shell Scripts to Find How Many Users are Logged In, Commands to get user-related information: · 1. id: The id command is used to print the user and group information for the specified USER.

Источник

Оцените статью
Adblock
detector