tags:

views:

46

answers:

4

In my bash script I execute some commands as other user. I want to call a bash function in command of su I defined in my script before.

my_function()
{
  do_something
}

su username -c "my_function"

The above script doesn't work, of course my_function is not defined inside su. I have only the idea to save the function into separate file. Any better idea, not to make other file?

+2  A: 

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

Gadolin
sudo is not enabled. System admin won't enable it.
Attila Zobolyak
+1  A: 

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.

Tuminoid
I'd like to call the same script outside su. The other script was my idea as well.
Attila Zobolyak
+1  A: 

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

export -f my_function
su username -c "my_function"
Dennis Williamson
A: 

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 :)

The Devil