Running bash function in command of su
Asked Answered
N

4

15

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?

Nebraska answered 16/9, 2010 at 11:30 Comment(0)
W
17

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

export -f my_function
su username -c "my_function"
Waterresistant answered 16/9, 2010 at 14:19 Comment(0)
P
2

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

Portauprince answered 16/9, 2010 at 11:40 Comment(2)
sudo is not enabled. System admin won't enable it.Nebraska
How do you do this with sudo? a simple sudo my_function will not work, even after exporting that function.Auxochrome
O
1

You must have the function in the same scope where you use it. So either place the function inside the quotes, or put the function to a separate script, which you then run with su -c.

Octal answered 16/9, 2010 at 11:41 Comment(1)
I'd like to call the same script outside su. The other script was my idea as well.Nebraska
L
0

Another way could be making cases and passing a parameter to the executed script. Example could be: First make a file called "script.sh". Then insert this code in it:

#!/bin/sh

my_function() {
   echo "this is my function."
}

my_second_function() {
   echo "this is my second function."
}

case "$1" in
    'do_my_function')
        my_function
        ;;
    'do_my_second_function')
        my_second_function
        ;;
     *) #default execute
        my_function
esac

After adding the above code run these commands to see it in action:

root@shell:/# chmod +x script.sh  #This will make the file executable
root@shell:/# ./script.sh         #This will run the script without any parameters, triggering the default action.        
this is my function.
root@shell:/# ./script.sh do_my_second_function   #Executing the script with parameter
this function is my second one.
root@shell:/#

To make this work as you required you'll just need to run

su username -c '/path/to/script.sh do_my_second_function'

and everything should be working fine. Hope this helps :)

Legging answered 16/9, 2010 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.