0

I have a shell script with two functions. The second function needs to be run as another user from a new bash shell. The first function is invoked into the second one. Function 1 uses some of the script variables.

#!/bin/bash
foo=bar
function1() {
    echo -e "$1"
}

function2() {
    echo "This is function2"
    function1 "I use function1"
    echo "I also need to print ${foo}"
}
export -f function2
su username -c "/bin/bash -c function2"

Actually this run function2 inside a new shell then fail to find neither function1 nor foo.

Is there a way to inject or pass them to the new function ?

2

This is a job for separate script files, not functions.

script1.sh:

#! /bin/bash
echo -e "$1"

script2.sh:

#! /bin/bash
echo "This is script2"
bash script1.sh "I use script1"
echo "I also need to print ${foo}"

And script.sh:

#! /bin/bash
foo=bar
export foo
sudo -Eu username bash script2.sh

Forcing the use of functions here will lead to a hacky, unmaintainable solution. Don't.

  • I know it's dirty .. I just can't refactor my colleague scripts for now ( This is just an exemple , real scripts are way more complexe) .. I would be thankful if you can add a functions implementation to this. – storm Jan 2 '18 at 14:56
  • @storm if it's complex, I'd recommend even more strongly: don't do it. Things will likely break. What you should do if you can't refactor is to run specific commands in function2 with su or sudo. – muru Jan 2 '18 at 15:01
  • Okay, that's fair enough thank you... I'll leave the question open in case someone have a handy solution. – storm Jan 2 '18 at 15:09
  • 1
    @storm checkout declare -f function1, which will give you the function1's declaration in reusable text. Then you could likely do something like sudo -Eu username bash -c "$(declare -f function1 function2); function2" – muru Jan 2 '18 at 15:13
  • 1
    (I should say: somewhat reusable text. It will break with even slightly complex quoting. printf "%q" might help with that, but, eh...) – muru Jan 2 '18 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.