bash run function with different user
Yes, this is possible
#!/bin/bash
function1(){
echo `whoami`
}
export -f function1
su username -c "bash -c function1"
exit 0
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.