在 su 命令中运行 bash 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3726195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running bash function in command of su
提问by Attila Zobolyak
In my bash script, I execute some commands as another user. I want to call a bash function using su.
在我的 bash 脚本中,我以另一个用户的身份执行了一些命令。我想使用 .bash 调用 bash 函数su。
my_function()
{
do_something
}
su username -c "my_function"
The above script doesn't work. Of course, my_functionis 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?
上面的脚本不起作用。当然my_function里面是没有定义的su。我的一个想法是将该函数放入一个单独的文件中。您有避免制作另一个文件的更好主意吗?
回答by Paused until further notice.
You can export the function to make it available to the subshell:
您可以导出该函数以使其可用于子shell:
export -f my_function
su username -c "my_function"
回答by Gadolin
You could enable 'sudo' in your system, and use that instead.
您可以在系统中启用“sudo”,然后改用它。
回答by Tuminoid
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.
您必须在使用它的同一范围内拥有该函数。因此,要么将函数放在引号内,要么将函数放入单独的脚本中,然后使用 su -c 运行该脚本。
回答by tftd
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:
另一种方法是制作案例并将参数传递给执行的脚本。示例可以是:首先创建一个名为“script.sh”的文件。然后在其中插入这段代码:
#!/bin/sh
my_function() {
echo "this is my function."
}
my_second_function() {
echo "this is my second function."
}
case "" 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 :)
一切正常。希望这可以帮助 :)

