Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Comments on As root, how do I read another user's environment variables?

Post

As root, how do I read another user's environment variables?

+4
−0

I have a script that should be run using sudo, with the goal of "promoting" a script from a user-level installation to a system installation. Reproduced here:

Existing code
#!/bin/bash

if [[ $EUID -gt 0 ]]; then
    echo "This script must run as root"
    exit 1
fi
if [[ -z "${SUDO_USER-}" ]]; then 
    echo "Sudo user not found"
    exit 1
fi
if [[ -z "${1-}" ]]; then
    echo "Usage: sudo share-command SCRIPTNAME"
    exit 1
fi
user_bin="$(getent passwd $SUDO_USER | cut -d: -f6)/.local/bin"
src="$user_bin/$1"
dst="/usr/local/bin/$1"
if [[ -f "$dst" ]]; then
    echo "Already exists"
    exit 1
fi
/usr/bin/install -m 755 "$src" "$dst"

Currently, it looks up the sudo user's home directory and looks in .local/bin relative to that.

I would like it to be able to find the script being installed by name.

I do not want to set the root user's PATH; I understand that this is insecure and there are protections against it. But given that the script is running as root, and I know who the sudo user is, it seems like I should be able to determine that user's PATH, and then iterate over it manually to look for the script.

Is this indeed possible? How?

History

2 comment threads

XY Problem? (5 comments)
Inversion of control (2 comments)
Inversion of control
r~~‭ wrote 7 months ago

If your script won't function unless it is run with sudo, perhaps it should run sudo itself?

#!/usr/bin/env bash
echo "Current user: $EUID"
echo "Do things not requiring root now, like searching \$PATH"

sudo env what_we_found="42" "$BASH" <<'EXIT_SUDO'

echo "In sudo"
echo "Current user: $EUID"
echo "Data from non-root: $what_we_found"

EXIT_SUDO
Karl Knechtel‭ wrote 7 months ago

Ah, I think that satisfies my use case quite well, in fact. But the general question still seems worth investigation. Maybe it can be edited into something more compelling?