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?
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.
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.
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).
You can export the function to make it available to the subshell:
export -f my_function
su username -c "my_function"
You could enable 'sudo' in your system, and use that instead.
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