0

Basically, I believe that this answer here by Bruno Bronosky could answer my question...

How do I redirect output to a variable in shell?

...but the way he wrote his code confuses me.

What I need is this:

  1. I have a vendor-proprietary script (small_script) that is really particular about which user runs it (only the logged in user).

  2. I have a larger script that I wrote to help installs on Linux, and I want my large_script to call this small_script.

  3. My large_script MUST be invoked by sudo (due to it installing a bunch of software)

  4. Small_script refuses to execute, if executed by sudo or root

  5. Possible solution is using variables:

    myuser=$(whoami)
    sudo -Hu ${myuser} ./small_script.sh
    

    This won't work because whoami reports as root since I just sudo'd the command

  6. So, I need to set a variable ($myuser) who's output is the output of whoami Before I can run those lines of code so it appears that the currently logged in user is the real person executing the code.

Again, it appears that the user Bruno Bronosky has the right idea, but I'm really confused on his answer:

# my example above as a oneliner
series | of | commands | (read string; mystic_command --opt "$string" /path/to/file) | handle_mystified_file

Code that doesn't work:

  1. sudo -Hu '# 1000' ./small_script.sh
    

    works, but I need it to run on the currently logged in user (which may not be userid 1000).

  2. sudo -Hu $USER ./script.sh
    

    This fails to run, it gives an error thinking that the username is null.

  3. myuser=$(whoami)
    sudo -Hu ${myuser} ./script.sh
    

    This errors out thinking it is root.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
benbrockn
  • 1
  • 1
  • 1
    `sudo -u $(whoami) foo` isn't really any different from `foo`; you aren't changing users. – chepner Jun 09 '19 at 21:24
  • *How* your vendor-provided script determines who the "logged-in user" is is a question that speaks a bit to what the right approach is, insofar as it's that script you're trying to satisfy. If that vendor-provided script is checking `SUDO_USER`, you want to do that. If it's checking the TTY's owner, you want to do *that* instead. If it's walking the process tree back to find the first non-root user, or [differentiating between active/saved/effective UIDs](https://stackoverflow.com/questions/8499296)... either way, if your goal is to duplicate its result, duplicate its methods. – Charles Duffy Jun 09 '19 at 21:54

1 Answers1

1

Fortunately, sudo provides environment variables (SUDO_USER and SUDO_UID) with the relevant user info, for situations just like this. You should be able to use this:

sudo -Hu "$SUDO_USER" ./script.sh

BTW, please ignore Bruno Bronosky's answer to that other question. He's going to great lengths to comply with the request for a "redirect", rather than a different operation that actually accomplishes the desired goal.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151