1

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.

1
  • 1
    Who runs the script? Are you wanting the user running the script? Commented May 31, 2014 at 15:15

5 Answers 5

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

You could also use "last":

$ last | grep "logged in"

Comments

1

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

Comments

0

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`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.