So I've got the following function, which executes another function (defined the same way, executed the same way this one is successfully called).
The reason for the syntax I've used here is to ensure the code is executed as a particular user- as I say, outside of functions, this syntax works with no issues.
f2(){
echo "test" > test.txt
}
f1(){
a=1
if (($a < 0 ))
then
echo "Not running function."
else
echo "Running function."
sudo su servuser -c "$(declare -f f2); f2"
fi
}
sudo su user1 -c "$(declare -f f1); f1"
Why is this the case? Is there a change that can be made to this code to allow me to call one function from another function as a certain user?
Any help would be most welcome :)
CodePudding user response:
When you execute a script using su
, that script has only access to the exported variables from your current shell script. You used $(declare -f f1)
to work around this issue, but forgot that the 2nd su
inside f1
loses access to f2
. When f1
executes su user -c '$(declare -f f2); f2'
there is no f2
so you cannot print/export it and therefore cannot execute it.
You have to explicitly include the dependencies of f1
in your first export:
f2() {
echo "test" > test.txt
}
f1() {
sudo su servuser -c "$(declare -f f2); f2"
}
sudo su user1 -c "$(declare -f f2 f1); f1"
By the way: Bash allows exporting functions.
f2() {
echo "test" > test.txt
}
f1() {
sudo su servuser -c f2
}
export -f f1 f2
sudo su user1 -c f1