Don't do this.
Getting the two lines of output in the wrong order should have been a hint that something was wrong.
When you execute your script using
ssh email@example.com 'bash -s' < script.sh
the following happens:
- The script is passed to
bash -s on the shells standard input stream.
- The script defines the
test function and calls it.
sudo bash command in the function starts a root shell.
- This shell inherits the standard input stream, which is the script.
- The root shell continues reading the script from the point after the function call. It does this because this is where the stream is at at this point.
Now you have a root shell started from within the
test function, which is executing instructions after the
- It starts a second root shell, which inherits the standard input stream (i.e. the shell script stream).
You now have a
centos shell executing a root shell, executing a root shell.
- The second root shell executes
echo "outside $(whoami)" outputting
outside root, which is the last line of the script.
- There is nothing more to read, so the second root shell terminates.
- So does the first root shell.
- The original
bash -s shell executes
echo "inside $(whoami)" (because it's part of the function that it started to execute earlier), outputting
- The shell function call exits and since the rest of the script has already been read by the two root shells, the original shell has nothing more to read and terminates.
sudo is strictly for executing another command (or starting an interactive shell). The change in user is for that other command only. When the command terminates, you are back as the original user. You can not use
sudo to "switch to another user" in the middle of a script and then run a part of that script as that other user (unless, of course, you deliberately write your script to be executed in the bizarre manner untangled above, but that sort of coding belongs in an obfuscated code contest).
To execute a set of commands as root in a script, you must give those commands to the
sudo invocation. For example:
sudo bash -c 'echo "Now running as $USER"; echo "whoami outputs $(whoami)"'
sudo bash -c command exits, you are back as your original user. Always.