How is it that I've been writing shell scripts for over 15 years now to automate processes, and I've only just discovered $SUDO_USER today? I feel like that's a MASSIVE oversight.

@twann @mike can either of you provide a link, or personal clarification what that is and how to use it?

@RyuKurisu Sure. Here's a script:


echo This is a script.
echo $SUDO_USER ran it.

If you run this as yourself, the output is:

This is a script
ran it.

If you run it with sudo, the output is:

This is a script
<username> ran it.

Where <username> is the account name you ran the script from. So, if my username is mike, it would say "mike ran it".

This really helps out with things like logging.


@RyuKurisu @twann @mike
Create a script like this,

[ $SUDO_USER ] && user=$SUDO_USER || user=`whoami`
echo -en "$user"

Then run it as a normal user and then with sudo and see what happens ;)


@hakerdefo @RyuKurisu @twann @mike Just to golf things a little,

echo ${SUDO_USER:-$USER} running as $USER

@mike @thorn @twann another nicety might be $SUDO_PROMPT: Used as the default password prompt unless the -p option was specified.

@mike I learned about -e last year or so. That was life changing for me.

-e Exit immediately if a pipeline (which may consist of a
single simple command), a subshell command enclosed in parentheses,
or one of the commands executed as part of a command list enclosed by
braces (see SHELL GRAMMAR above) exits with a non-zero status.

@mike huh… didn’t know that exists. Thanks!

@mike Well, I didn't know either. And after I checked the man page of sudo, I found there are many $SUDO_* environment variables.


@mike BTW I find it funny that I learn something about `sudo` whereas I'm starting to use `doas` on Alpine Linux :thaenkin:

Maybe I should check out the manpage of `doas` to learn all its niceties? :allthethings:

Sign in to participate in the conversation

Fosstodon is an English speaking Mastodon instance that is open to anyone who is interested in technology; particularly free & open source software.