Score:0

get the username of the user who called script with sudo

us flag
J'e

How do I get the username from within a script that was called with sudo? In other words, I don't want root but the actual username.

echo_user.sh

#!/usr/bin/env bash

echo whoami

Calling the script from user pikachu, I would expect it to print pikiachu and not root.

sudo ./echo_user.sh

There are lots of post from around 7 to 12 years ago with this exact question. None of them seem to work on Ubuntu 22.x. I'm simply trying to get the name of the user that called a script with sudo. Most of the old examples reference SUDO_USER but the only way I've been able to get it to work is by running sh -c 'echo $SUDO_USER'. echoing SUDO_USER from a script shows it's undefined.

Esther avatar
es flag
it should be defined in a script, that's weird. Works for me in 20.04 WSL, and I don't know that anything has changed before 22.04/22.10
Esther avatar
es flag
what were you doing in your script that was different from the answer below?
Score:4
tn flag

Try this:

#!/usr/bin/env bash

echo "$SUDO_USER"
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.