문제

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?

도움이 되었습니까?

해결책

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.

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.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top