Stefano Radaelli
Stefano Radaelli

Reputation: 1118

bash run function with different user

Would be possible to run a custom bash function with different priviledges?

#!/bin/bash
function RunStefano() {
     while [ 1 ]; do
         echo "Ciao, ´/usr/bin/whoami´"
         sleep 10;
     done &
}
export -f RunStefano;
echo "Welcome, ´/usr/bin/whoami´"
sudo -u stefano -c "RunStefano"

If I run this script with 'root' user, I want to receive as output:

Welcome, root
Ciao, stefano
    (...)
Ciao, stefano

Would it be possibile?

Upvotes: 16

Views: 13757

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263237

You can't do that, at least not directly. (But see Richard Fletcher's answer.)

Each process runs under a particular user account. By default, that's the same account as the process that invoked it. sudo lets a process running under one account launch another process that runs under a different account.

When you invoke a shell function, it doesn't launch a new process. With some modifications, your script should give you something like:

sudo: RunStefano: command not found

In the new process created by sudo, there is no RunStefano command; the function is local to the process running the script.

You need to isolate the function into a separate executable script; you can then invoke that script via sudo.

Incidentally, you also need to change the apostrophes around /usr/bin/whoami to backticks:

echo "Ciao, `/usr/bin/whoami`"

And you should read the documentation for the sudo command; it doesn't have a -c option.

Upvotes: 6

Richard Fletcher
Richard Fletcher

Reputation: 431

Yes, this is possible

#!/bin/bash
function1(){
   echo `whoami` 
}
export -f function1
su username -c "bash -c function1"
exit 0

Upvotes: 32

Related Questions