I tried exporting the function and then executing it with bash, but that doesn't work:
$ export -f my_func $ sudo bash -c 'my_func' bash: my_func: command not found
If I try to run the function with bash without sudo (bash -c 'my_func'), it works.
Any idea?
To give root privileges to a user while executing a shell script, we can use the sudo bash command with the shebang. This will run the shell script as a root user. Example: #!/usr/bin/sudo bash ....
sudo allows users to run programs with the security privileges of another user (normally the superuser, or root). bash starts a new bash shell. So, sudo bash starts a new bash shell with the security privilege of root user.
In order to run a Bash script on your system, you have to use the “bash” command and specify the script name that you want to execute, with optional arguments. Alternatively, you can use “sh” if your distribution has the sh utility installed. As an example, let's say that you want to run a Bash script named “script”.
Each time you run sudo, it forks and execs a new copy of the shell, running as root. That shell does not inherit functions from your shell (it can't) and it doesn't inherit functions from previous executions. You will have to write out a file containing the function definition and invocation and sudo the invocation of that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With