fabou3377
fabou3377

Reputation: 23

Get current user on root script ubuntu

I write a script for the network dispatcher in /etc/NetworkDispatcher/dispatcher.d/. How can I get the current logged user?

I already tried these commands :

$USER
$LOGNAME

Thank you for help.

Upvotes: 1

Views: 2146

Answers (5)

Mario Palumbo
Mario Palumbo

Reputation: 1007

This command should be ideal in your case:

logname

The logname command displays the login name of the current process. This is the name that the user logged in with.
Source: https://www.ibm.com/docs/zh/aix/7.1?topic=l-logname-command

You can display or print the name of the current user (also know as calling user) using logname command. This command reads var/run/utmp or /etc/utmp file to display the name of the current user.
Source: https://www.cyberciti.biz/faq/unix-linux-logname-command-examples-syntax-usage/

The logname utility explicitly ignores the LOGNAME and USER environment variables because the environment cannot be trusted.
Source: https://man.openbsd.org/logname.1

Upvotes: 1

Marek Möhling
Marek Möhling

Reputation: 152

I needed this for a postins script in a deb file, nothing of the above worked, but this did on LinuxMint 19.3 (tricia):

`users`

Upvotes: 0

hft
hft

Reputation: 1245

You could also use "last":

$ last | grep "logged in"

Upvotes: 2

Kaoru
Kaoru

Reputation: 1570

If running a script with /usr/bin/sudo you can access the original user from the $SUDO_USER environment variable.

For example if this is the contents of a script test.sh:

#!/bin/sh

echo "USER:      $USER"
echo "SUDO_USER: $SUDO_USER"

Then if you run it as "alex":

alex@yuzu:~$ ./test.sh 
USER:      alex
SUDO_USER: 

And if you run it via sudo:

alex@yuzu:~$ sudo ./test.sh
USER:      root
SUDO_USER: alex

Upvotes: 5

konsolebox
konsolebox

Reputation: 75608

You can use whoami. Or perhaps you could get a list of users logged-in with users. It really depends on what you need specifically.

Upvotes: 3

Related Questions