0

I would like to enable sudo within this bash function mid-script. I believe the issue is that sudo -s opens up a new shell, and all subsequent lines aren't printed because the shell is exited.

function example {
    echo "one"
    sudo -s
    echo "two"
    echo "three"
}

How can I have two and three also get printed as sudo? Without adding sudo before each?

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • 1
    Possible duplicate of [how to run two commands in sudo?](https://stackoverflow.com/questions/5560442/how-to-run-two-commands-in-sudo) Also, an option using a heredoc is [at this link](https://stackoverflow.com/questions/3435312/how-can-i-execute-a-series-of-commands-in-a-bash-subshell-as-another-user-using) which is a little prettier. – JNevill Jan 10 '18 at 16:34

2 Answers2

0

What about a double function? Can that help?

#!/bin/bash 
function test2 {
sudo echo "two"
sudo echo "three"
}
function test {
echo "one"
test2
}
test
0

Try this in your script test.sh:

#!/bin/bash
testfunc() {
echo "test";
sudo sh -c "echo 'haha'";
echo "hooo";
}
testfunc;

Then call it with:

bash test.sh

Drasz
  • 41
  • 7