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.

Follow

@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:

#!/usr/bin/sh

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.

@twann

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

#!/bin/bash
[ $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 ;)

Explanation,
sudo.ws/man/sudo.man.html#SUDO

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

#!/bin/sh
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.

Sign in to participate in the conversation
Fosstodon

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