Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running bash function in command of su

Tags:

bash

shell

su

In my bash script, I execute some commands as another user. I want to call a bash function using su.

my_function()
{
  do_something
}

su username -c "my_function"

The above script doesn't work. Of course, my_function is not defined inside su. One idea I have is to put the function into a separate file. Do you have a better idea that avoids making another file?

like image 340
Attila Zobolyak Avatar asked Sep 16 '10 11:09

Attila Zobolyak


People also ask

How do I run a bash function in terminal?

To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.

How do I run a command with su?

su Command Options–c or –command [command] – Runs a specific command as the specified user. – or –l or –login [username] – Runs a login script to change to a specific username. You'll need to enter a password for that user. –s or –shell [shell] – Allows you to specify a different shell environment to run in.

What does $() mean bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).


2 Answers

You can export the function to make it available to the subshell:

export -f my_function
su username -c "my_function"
like image 53
Dennis Williamson Avatar answered Oct 16 '22 04:10

Dennis Williamson


You could enable 'sudo' in your system, and use that instead.

like image 27
Gadolin Avatar answered Oct 16 '22 03:10

Gadolin