Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute a bash function using sudo?

Tags:

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?

like image 809
Miroslav Avatar asked Feb 25 '12 23:02

Miroslav


People also ask

How do I sudo a bash script?

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 ....

Does sudo work in 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.

How do I run a bash shell?

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”.


1 Answers

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.

like image 89
bmargulies Avatar answered Oct 05 '22 06:10

bmargulies